Making a Simple and Efficient Cool Down Timer in Unity

No Cool-Down Timer

One key figure to any weapon in a game is it’s fire rate or attack rate. And is one of the many systems we as developers must build from scratch to put into our games.

There are quick and easy ways to get the needed effect. But the way I will show you pulls some of the work out of the Update loop, which is always good when trying to improve the performance of any game system.

First, we will want a bool to let us know whether or not we can fire our weapon (laser).

Boolean for our Laser firing ability.

Now we can add this to the check to see if the ‘fire’ button has been pressed.

A two condition IF statement

As you can see we are using the double & logic operator. This is a conditional AND that will only check the second condition if the first is true instead of always checking both conditions. This cuts down on number of checks being made and should be used in most cases.

Now we need a timer to turn _laserCanFire true after a given time. For this we will use a CoRoutine in the form of an IEnumerator.

With the use of yield, IEnumerators allow us to delay some bit of code while the rest of the program continues on it’s job. It is one of the few places you can feel a little more comfortable using a while statement.

Here we wait for half a second after the coroutine has been started to turn the bool _laserCanFire True again.

Now to add all the pieces together to get a working system.

Full code for Laser firing method

Here we set an offset for the laser to fire just in front of the ship, then instantiate it. I’ve also included the ships rotation and parent information for future uses.

Then we set the _laserCanFire to False to prevent the player from firing again right away. And we start the LaserReloadTimer coroutine for it to reset it in half a second.

Cool-down timer Implemented



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
Thomas Kesler

Thomas Kesler

A Unity Developer with a fondness for Fantasy games and the challenge of pushing boundaries.