Creating a Cooldown System in Unity

Hades from the Hercules cartoon, has a temper but chills out. Caption: “Okay, fine, fine. I’m cool. I’m fine.”
Be the chill.

In our last article we made our budding space shooter… shooty. But is it too shooty? We don’t want to look like a Shooty McShootface. We wanna be a chill shooter. A shooter who knows how to play it cool. We need a cooldown system.

Frigid puns aside, let’s think of a way we can restrict the player from covering the field in lasers by spamming the spacebar with a key repeater bot. All the shooting happens in the Player script, so open that up. Time for some pseudo code:

// if the spacebar is pressed AND the cooldown time is up

But the tricky part is, how do we know if the cooldown time is up? Well, we already used Time.deltaTime in our movement script to tie our rate of speed to the rate of the game clock. So, we can do something like that here using Time.time.

First, I’ll declare a couple of new variables:

 private float _fireRate = 0.15f;
 private float _canFire = -1f;

The first is the rate of fire in seconds. The second is going to hold the target clock value when the player will be allowed to shoot again. All we have to do at runtime is add the fire rate to the current Time.time and set _canFire to that sum each time the player hits the spacebar. If the player hits it again before the condition is met, no laser will fire. The code looks like this:

if (Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
This portion is within your update method and replaces the old fire conditional.
void FireLaser()
 _canFire = Time.time + _fireRate;
 Instantiate(_laserPrefab, transform.position + new Vector3(0, 0.8f, 0), Quaternion.identity);
We add the time calculation into the FireLaser method.

And that’s it. A simple, and easy way to add a cooldown timer to any ability. You can easily tweak the timing of this in the inspector while playing to alter the feel or challenge of the game. And no matter what, you’ll look cool doing it.

In the next article I’ll tell you a bit about physics in Unity.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store