Project 1: Space Shooter

Simple yet effective cooldown system in Unity

With an example of cooling the lasers

No matter how fast the spacebar is pressed, this laser with a cooldown system cannot be any faster.

Just to annoy the trigger happy people and give some chance to our poor enemies, I will show you how to make a simple and effective cooldown system by implementing one for my Laser Prefabs.

To begin creating the cooldown system I head down to my Player script and make two private float type variables. These are called to handle how often the lasers can be shot, and to indicate if the laser can be fired.

This can be achieved by adding an additional argument to the firing mechanism. Namely the laser can be shot if the spacebar is pressed and the cooldown has passed. For this to happen I have to somehow know how much time has passed from the last shot.

Thankfully Unity provides an easy way to do this with the class Time and its method time. This returns the time from the start of the game as a float value. So to use this as a logical argument I have to compare it with the variable, that is when the Time.time value is greater than the value in can the laser be fired.

Script for creating a simple cooldown system.

For the player to be able to fire for the first time I set the initial value to be -1f, it could be zero as well, but this is easier to see and understand when reading the code. Once the laser has been fired I have to add the cooldown for it.

Here the Time.time plays a role as well, because by adding the to the float given by the Time.time and saving it into the I have effectively produced a cooldown system. Since now the value in is larger than the current Time.time at maximum of the value in , will the argument in the if-statement evaluate to and thus the laser will not fire.

And that is how a simple cooldown system can be created 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