Creating A Simple Cool-down System in Unity
In this article, we will create a cool-down system for the shooting system made in the previous article.
Right now, the Player can fire as fast as they can press the space bar.
Which is way too fast for what this system is being designed for. So that means we need to put in a cool-down so the Player can only fire when the cool-down period is over.
To start creating the cool-down open the Player script. The first thing we will need is to create a variable for the amount of time between shots. Create a public float named fireRate with a value of 0.5. The next thing we need is a variable to hold the amount of time that needs to pass before we can fire again. Create a private float named _canFire and no value, which defaults it to 0.
Next, the logic for the cool-down needs to be implemented. In void Update, change the if statement’s condition to include another condition using the && operator, which means AND. Using the && operator requires both sides’ conditions to be true for the if statement to be executed. The second condition is that Time.time the amount of time since the start of the game, needs to be greater than _canFire. Inside the if statement, make it so _canFire will be set to equal Time.time + fireRate when a shot is fired. That will make it, so _canFire is now 0.5 higher than the current Time.time causing the second condition to be false and creating a cool-down till Time.time catches up.
Now that the Player is firing once every 0.5 seconds, the cool-down system is complete. Time to clean up void Update and put the firing logic in it’s own method.
Create a new method named “FireLaser”. Then, copy and paste the logic inside the if statement into the FireLaser method and then call the method in the if statement in the void Update.
With the code cleaned up and the cool-down system working, that is the end of this article.