Creating a Cooldown System in Unity

Lance Gold
2 min readMar 18, 2024

--

This is a system to slow down the rate of shots fired from whenever a key is pressed to only one shot ever so often: once per second, twice per second, or any predetermined time between shots.

This first picture shows the rate of firing dependent on rapid key presses.

shots fired based on rapid key presses only

To slow the rate of fire down to every 0.5 seconds, take a look at the following idea:

  • fire a shot and note down the time of the shot
  • ignore keypresses until time + 0.5 seconds
  • fire a shot and note down the new time of the shot

Using the Shooter game example, the code logic is placed in the Player class next to where key presses and Laser clones are instantiated.

public class Player : MonoBehaviour
{
private float _canFire = -1.0f; // updates to next okay to fire time
[SerializeField]
private float _fireRate = 0.5f; // time between firing each shot

The _canFire starts out negative to allow the first shot fired.

    // Update is called once per frame
void Update()
{
// if I press spacebar and cool down period is over then
// instantiate clone object
if (Input.GetKeyDown(KeyCode.Space) && ( _canFire < Time.time))
{
_canFire = Time.time + _fireRate;

//Instantiate(_laserPrefab)
}

Here is the result:

Player object firing only after half second cool down interval

Now because the _fireRate is also a [SerializeField], we can adjust the interval during runtime in the Inspector view.

Fire Rate is visible in Inspector for making adjustments

--

--

No responses yet