Creating a Cooldown system in Unity

Day 9- Making 2D Space Shooter Game

In the video above, you can see that even though I am pressing the Space key really fast, the fire rate is always the same or even late. On the inspector panel, you can see that the fire rate is set to 0.5 and it is creating a cooldown system in our player.

To create a cooldown system, you first need to create two variables. One to hold the value as to when your player is able to shoot again and one to store the value for how long you want the delay to be.

Here, my player will be able to fire once every 0.5 sec.

Here, in my Update you can see that when player presses the space key, the Input condition is true and when Time.time is greater than _canFire then fire the laser, it returns true thus calling the FireLaser function..

So what is Time.time and how is it helping create a cooldown? The answer is simple, it gives you a numeric value which is equal to the number of seconds which have elapsed since the project started playing. So if you played the game for 5 sec, you get the value of Time.time as 5sec.

So the first laser shoots when you press Space key but since the _canFire is always 0f, you will be able to fire continuously. What can we do to prevent that? we set the _canFire value to be _fireRate more than that of Time.time

Here, whenever the player presses the space key and Time.time is greater than _canFire, the condition is true and it calls a method FireLaser(). Inside this method, you are replacing the current _canFire value with new value which is _fireRate value more than the current Time.time.

This means that until the Time.time reaches the current _canFire value with takes 0.5sec, the player won’t be able to shoot again thus successfully creating a cooldown system.



Unity Developer

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