Creating a Simple Cooldown System in Unity!
Now that we have given our player a “deathly” laser ( read about it here! ), we have to create a cooldown system so that the gameplay won’t get boring with just spam-mashing that ‘Fire’ key.
The key function we are going to use to solve this problem is ‘Time.time’. This read-only function returns the time in seconds since the start of the game.
Unity’s Update Loop is running at 60 frames per second, meaning if a player could smash the ‘Fire’ key 60 times per second, the laser would fire that many times. So we need to figure out how to prevent our player from doing just that.
Cooldown System Implementation
First up, we will be defining a ‘_fireRate’ variable. This variable will give us an exact rate of fire for the player. We will also serialize this variable in case we would like to change it in the ‘Inspector.’
We also initialized a ‘helpful’ variable called ‘_canFire.’ Next up, we are going to be adjusting our ‘FireLaser()’ method. In this method, we will be summing the time.Time function with the ‘_fireRate’ variable and storing that in our newly created ‘_canFire’ variable. This will return to us the exact time from the start of the game when the last shot was fired. The ‘FireLaser()’ method should now look something like this.
Finally, we have to adjust our Update Loop to check if the last shot fired was fired sometime in the ‘_fireRate’ window and if not only then allow the player to shoot. To do that, we adjust our if statement and add another check like this.
And that is that - We have successfully implemented a cooldown system! Feel free to play around with the ‘_fireRate’ value in the ‘Inspector’ to get the feel you wish to achieve, just right.
But that is it for now, thank you for reading and feel free to follow me for more articles — and as always, good luck and see you next time!