Creating a Cooldown System in Unity

Slowing Down the Firing Power

James Hills
2 min readMay 3, 2022

In my sample 2D Space Shooter game, the ability to constantly fire a laser as fast as I could press the keyboard was not what I wanted.

Firing Without Cooldown

In order to change this, I had to implement a Cooldown System.

The first thing I did, was look at my “Player” script. I needed to add some time logic to my code to let the system know how much time had passed.

  • In my “Player” script, I created a private float variable named _fireRate and assigned a value of 0.5f. I used the [SerializeField] attribute so it can be changed while in game testing, just to make sure 0.5f was going to work. I then created another private float variable named _canFire with a value of -1f, which will be used to calculate the time passed.

[SerializeField]
private float _fireRate = 0.5f;
private float _canFire = -1f;

Create Firing Variables

Next, I had to add some more code to the “Player” script to implement the time constraint on the rate of fire. I used “Time.time” to get the amount of time the game has been running.

Now, I can calculate what time in the game the player pressed the fire button and assign a new value to that time. Then I check the difference to see if 0.5 seconds have passed. If it has, the player can fire again. If it hasn’t, the player will have to wait until the system shows 0.5 seconds have passed. The code is written in the “Player” script inside the method used to get the key input and GameObject Instantiation.

if (Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
{
_canFire = Time.time + _fireRate;
Instantiate(_laserPrefab, transform.position + new Vector3(0, 0.85f, 0), Quaternion.identity);
}

Now, the firing is more controlled. There is a cooldown after each firing.

Firing With Cooldown

Thank you for reading my article. I hope you found it informative and helpful.

--

--

James Hills
James Hills

Written by James Hills

I am a married father of 5 children. I decided at 13 years of age that I was going to become a Software Developer.

No responses yet