Creating A Cooldown System in Unity

Sometimes you don’t want to let the player shoot as fast as they can click, even more so with macros that can click so much faster than any normal person ever could.

Can be useful if you want a machine gun but in this case, we want to put a limit on how fast you can shoot. This is where the cooldown system will be useful.

Let’s take a look at 2 different kinds of cooldown systems one using a Coroutine and the other using Time.time.


A coroutine is a function that allows pausing its execution and resuming from the same point, which is perfect for what we want. Shoot, pause, shoot. Now how do we go about this? If you google Coroutine for unity you will see something called IEnumerator. Looking at the examples given, IEnumerator (name)(){ yield return new WaitForSeconds(waitTime);} is what we need.

Let’s use a bool to change being able to shoot or not and a variable we can change to set that wait time to really dial it in. They go in before your first method.

Can fire is set to true for a start so we can get the first shot in before making it so we can’t shoot for a bit.

Now we can put _canFire = true just under the yield on the IEnumerator and to change out the set time to a variable we can change, just in case we want to change it later on.

This will bring back the ability to shoot again. Now to remove it, so that it can come back.

Which we can do in a shooting method using the Instantiating part from the Instantiating and Destroying article, with a simple _canFire = false; and a very vital part, starting the coroutine.

The new Vector3 part is putting an offset to the bullet so it doesn’t spawn inside the player.

Almost there, 1 last thing to do. When we press the space bar to shoot we need to check if we can shoot.

Using && is how you say And, so key pressed down And _canFire is true. for OR it’s using ||

And with that, it should all be working nicely.

This is with a fire rate of 0.2f


Time.time is how long the game has been running, in seconds. Like the coroutine, we will need 2 Variables just under the class. This time the _canfire is a float since we are going to check it against how long the game has been running.

Next, we will want to check if Time.time is greater than _canfire and if so, we can fire away.

Almost done!

This is where the real delay comes in, by adding the fire rate to Time.time and saving that into _canFire, there will be a delay before we can shoot again.

As you can see, this is a lot simpler than using a coroutine.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store