Unity3D: Creating a Cool Down System
Without a cool-down system, I can shoot infinitely when I hit the input button as fast as possible. This is a behavior that needs to be restrained. Every type of weapon has a fire rate. So why not implement a cool-down system?
I want there to be a .5 second delay when we shoot. So we need to figure out how to pass time in Unity and that would be:
Time.time
It allows us to track time in seconds once a game starts.
We also need a variable named “_canFire” of type float to determine if we can shoot. We will declare it with a value of 0.
We’ll also need our rate of fire for our weapon. In other words, a delay variable.
And if we want a designer to adjust it in the inspector, we can apply the SerializeField attribute:
Let's have a look at our current shooting logic without the cool-down:
Let’s check to see if Time.time is greater than _canFire. If it is, then we want to execute the body of the if statement:
The _canFire variable is the sum of the Time.time in seconds + _fireRate. If Time.time is 1 and it is greater than _canFire (value of 0) then it will result to true.
_canFire will have the sum of 1 from Time.time plus the _fireRate of 0.5.
_canFire will now have a value of 1.5.
Time.time will check again to see if it is greater than 1.5. Time.time has the value of 1 and counting. So it will be false until it reaches 1.6. We can now shoot again. We shoot.
_canFire now has the value of 2.
Time + the fire rate will keep on adding to the _canFire variable every time the player shoots.
This is the result of a simple cool-down system. I hope you learned something from this!
Thank you for reading :)