Day 9: Creating a Cooldown System in Unity

Blake Zoeckler
3 min readApr 28, 2021
Lasers are produced as fast as I can hit space.

Last time, we allowed the player to create lasers by hitting space. However, in a real game, having to hit space repeatedly is annoying. Lets change the fire method so we can just hold space instead. We can do this by replacing Input.GetButtonDown with Input.GetButton. This will allow us to fire lasers just by keeping space held down.

I’ve also changed the laser position to be offset slightly upward.

What’s the worst that can happen? Let’s just play the game, hold space, and-

Welp. That sure is a lot of lasers.

The issue here is that the lasers can fire every single time the game runs the Update method on the player, which can happen 60 or more times per second! The player would clearly be too powerful if we allowed this. So lets try restricting how often the player can shoot by using some new variables in the Player script.

Note that _cooldownTime is not serialized, so it won’t show in the inspector

The idea here is that _cooldownTime is constantly “counting down” every time the player is updated. When it reaches zero or less, that’s our cue that the player should be able to fire another laser. We then add to the if-statement using the && (and) operator, so that the laser only fires when space is pressed AND the cooldown time has indeed hit zero. Finally, once the laser fires, we reset the timer back to whatever the _fireRate is, so we once again have to wait that much time before firing.

As you can see, now the lasers shoot in a much more controlled fashion, even while the space bar is held down. We can even modify the fire rate while the game is running, which may potentially be some sort of “powerup” for this game in the future!

--

--

Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.