Cooling Down in Unity

Josh Vang
2 min readApr 16, 2021
Unfortunately, this cube doesn’t have auto fire enabled

Unless the player is using an automatic weapon, you would most likely want to implement a cooldown system to ensure the player doesn’t spam or hold down the Fire button.

Simple Way to Implement It

Although there are many ways to achieve this goal, one of the simplest way requires an if-else statement and a few variables, especially if the weapon launches a projectile.

private float _fireRate = 0.5f;
private float _canFire = 0f;
if(Input.GetButton("Fire") && Time.time > _canFire
{
_canFire = Time.time + _canFire;
Instantiate(projectile, transform.position, Quaternion.identity);
}

In this code excerpt, whenever the player presses the Fire button, it’ll check to see if the time passed is greater than the time delayed assigned to it. If it is, add the time passed to the time delay and generate a clone of the projectile.

Technical Breakdown

  • _fireRate is the time delay you want to in seconds. In this case, it’s 0.5 seconds
  • _canFire is a variable to store the delay. Because it’s a global variable, it’s set as 0 for the time being.
  • Input.GetButton(“Fire”) is asking when the player presses the Fire button, set this part of the if statement to true
  • Time.time is the amount of time, in seconds,that has passed once the game has started.

--

--