Project 1: Space Shooter
Simple yet effective cooldown system in Unity
Just to annoy the trigger happy people and give some chance to our poor enemies, I will show you how to make a simple and effective cooldown system by implementing one for my Laser Prefabs.
To begin creating the cooldown system I head down to my Player script and make two private float type variables. These are called _fireRate to handle how often the lasers can be shot, and _canFire to indicate if the laser can be fired.
This can be achieved by adding an additional argument to the firing mechanism. Namely the laser can be shot if the spacebar is pressed and the cooldown has passed. For this to happen I have to somehow know how much time has passed from the last shot.
Thankfully Unity provides an easy way to do this with the class Time and its method time. This returns the time from the start of the game as a float value. So to use this as a logical argument I have to compare it with the _canFire variable, that is when the Time.time value is greater than the value in _canFire can the laser be fired.
For the player to be able to fire for the first time I set the initial value to be -1f, it could be zero as well, but this is easier to see and understand when reading the code. Once the laser has been fired I have to add the cooldown for it.
Here the Time.time plays a role as well, because by adding the _fireRate to the float given by the Time.time and saving it into the _canFire I have effectively produced a cooldown system. Since now the value in _canFire is larger than the current Time.time at maximum of the value in _fireRate, will the argument in the if-statement evaluate to false and thus the laser will not fire.
And that is how a simple cooldown system can be created in Unity.