My very first project: Space Shooter
Captain our lasers are running too hot!
Just to annoy trigger happy people and give some chance to our poor enemies, I will show you how to make a simple 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 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 _canFire is a float larger than the Time.time until the time saved into the _fireRate has passed.
And that is how a simple cooldown system can be created in Unity.