How to Create a Cooldown system in Unity
Using Time.time
A Cooldown system is used to prevent certain things repeat indefinitely. There could be an RPG game with abilities you can only use once every few seconds for example. Another case could be when you can hit the fire laser button as many times as the machine can process it you will end up with something this:
(Sometimes this might look what you want, but this is still dependent on the machine capability. This could means a faster machine can hit the enemy more times per second, since it has more shots stacks even if you can’t see it)
Our example will be creating a cooldown system for shooting lasers.
Pseudocode — Shooting Lasers with Cooldown
With a google search you’ll quickly find the code on how to create a cooldown or fire rate in our case.
We could just copy paste that, but let’s try to understand the logic by translating the found code back to in pseudocode.
Set _nextFire to zero
Set _fireRate to 0.25
If the Fire1 button is pressed AND Time.time is greater then _nextFire
then _nextFire becomes Time.time + _fireRate
— and spawn the laser at player position with offset with same rotation as player
The first four lines are what matter for our cooldown system, so we can ignore the last line.
Time.time means the current running time of the game. When the game starts running Time.time becomes greater then zero, thus we meet the condition to be able to shoot. The moment we fire a laser the current running time plus the time we set in our fire rate are added to each other and stored in _nextFire (next time we can fire). The next time the condition to fire can be met is when the game running time is greater then the time of our last shot plus our value of fire rate.
The code example
[SerializeField] private float _fireRate = 0.25f;
private float _nextFire = 0f;
//When fire is pressed AND current game time is greater then previous laser fire time + fire rate(cooldown)
if (Input.GetButton(“Fire1”) && Time.time > _nextFire)
{
_nextFire = Time.time + _fireRate;
//instantite laser + Y offset
Instantiate(LaserPrefab, transform.position +_laserOffset, Quaternion.identity);
}
With this code we can hold the Fire1 button down and keep shooting with a set fire rate.