Cooldown Systems in Unity with C#

David Little
3 min readMay 14, 2021

Put simply, a cooldown system is used to restrict the rate of fire that the player is capable of. Without one the player could just fire as fast as they are physically capable of or that the hardware they are using will allow. Before we look at how this is done, some definitions are in order.

The first has to do with asking the question “How long has the game been running?” This is answered using Time.time, which tells you…exactly that, in seconds. Or more specifically, the time at the start of that particular frame. So, it is reporting the amount of time that has passed at the completion of the last frame played. ….whew.

So how is this useful to us? Well, we want to limit the rate of fire based upon the amount of time that has passed since the last shot was fired. Wee nee to know the current time, when the last shot fired and how much time we want to pass before the next fire can be shot. We need some variables.

First is our rate of fire which we are going to call _fireRate and the second is going to be called _canFire, which will be used to determine when the next shot can be fired. They are assigned initial values and are Serialized so that they can be tweaked from within the Unity editor.

Next we need to connect this logic to the actual action of firing the laser, which is done when the space bar is pressed down. So we will make our connection with the Input method, inserting it right after the KeyCode with an &&, as shown and in the Update of the script.

This method basically watches the clock, Time.time, and compares it to the amount of time that has passed since the last shot was fired plus Time.time. Once Time.time becomes greater than Time.time plus the time since the last shot was fired…you can then fire. The difference between the before and after implementation can be seen here.

Before
After

You can see, in the Hierarchy panel, that the maximum number of shots in the game drops down to three. This was with the _firaRate variable set to 0.3f seconds between shots. No matter how fast I repeatedly press the space-bar, lasers cannot be fired more than once every 0.3 seconds.

This cool down cylce is important for adjusting the realism or level of difficulty. Obviously, the fewer times that you CAN fire, the more difficult the game is going to be.

Soon we’re going to need to ad something to shoot at in this game. We’ll do that next time.

--

--