Unity3D: Creating a Cooldown System

Caleb Breuner
4 min readJun 4, 2021

--

…How to cooldown the rate of fire for a 2D Space Shooter Game.

Objective: The lasers in a space shooter need to have a fire rate so the player has a cooldown.

In order to create the cooldown, we need to write logic that will add a delay whenever the space key is pressed. We must keep in mind that whenever a variable is used whose value is an amount of time, it will reference the time of the program running. Whenever we need to reference the time within a program, we can use Time.time within the Update class.

Time.time is the time at the start of the frame. To reiterate, the Update class, it is running all the code within itself each of the 60 frames within the second. Time.time is a record of the time whenever the Update class runs.

Therefore, we must make sure we reference the current Time.time and add a delay to it. We will need to include a variable that represents the delay-in-time value. Since the Time.time is always updating, however, we will need another variable that will update the time-stamp value whenever the space key is pressed.

We will be modifying the same Player script that was made in the previous tutorials.

First, a variable for the delay will be created and named _fireRate. Its value for now will be 1 second.

Next, we will create a variable that will function as the time stamp which is permissible for the laser to fire. For now, we will make this 0 seconds from when the space key is pressed and will later update it as time goes on.

Next, we will be revisiting the if statement that contains the Instantiate() within the Update class in the Player script. Right now, it says: if the space key is pressed, create the assigned game object.

We will change this if statement to include another condition:

…if the space key is pressed AND the current time of the updated frame is greater than the permissible time stamp the laser can fire….

….then update the the permissible time stamp the laser can fire to be the time stamp of the frame the space key is pressed PLUS the delay the laser has to wait in order to be fired again….

….In addition, continue spawn the _laserPrefab within the if statement.

With the Player script saved, our lasers will now be generated at a much slower rate despite how many times we press the space bar key.

Within Unity, the _fireRate can be adjusted to a different delay to a smaller value, thus increasing our fire rate.

Success! Tutorial completed! Please make sure to visit my Medium page to see other tutorials regarding C# and Unity3D.

--

--