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.
Coroutine:
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.
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.
Almost there, 1 last thing to do. When we press the space bar to shoot we need to check if we can shoot.
And with that, it should all be working nicely.
Time.time:
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.
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.