Let’s slow it down now…
Implementing a cooldown system in Unity
Yesterday we looked at swapping out our firing code to use Unity’s new Input System. Currently, our player can fire as many shots as number of times that they can hit the space bar on the keyboard.
Today’s objective is to limit the number of shots our player can fire in a given time frame. To do so, we are going to create a cooldown system that disables the action taken when our fire button is pressed for a specified amount of time.
Let’s start by creating a placeholder for the minimum amount of time between laser shots that we want to enforce. We want this to be editable by designers in the future, so we will make sure to mark it as a Serialized Field, giving us access to it in the Unity Editor. Let’s also set the initial value to 0.5. This will ultimately give us a minimum time between shots of 1/2 a second. This value may be too slow for good gameplay, but we can adjust it later if needed and it will effectively display the delay we are implementing.
The way we are going to determine if we can re-enable the ability to fire after the cooldown time has elapsed depends on Unity’s
variable. Time.time contains the value in seconds that the game has been running. So if the game has been running for 5 minutes, Time.time will contain the value 300. At the time that the player fires a laser, we are going to add a delay equal to our fire rate to Time.time
and store it in a variable
so that we can check it against the current time in future requests for the fire button event. We’ll initialize this variable to -1 so that we know the first time we check the variable it will always be less than the current time and will allow us to fire. This results in our OnFire method looking as below
Now we need to check our current time against this value every time a request for firing a laser is made, triggering our OnFire method. If the specified time delay has elapsed, we allow the instantiation of a new laser object. We also only want to run this check if OnFire was triggered as the result of a key down event because that is how our fire code is currently set up. We can combine the checks as below
Hopping back into Unity and running the project shows that we have successfully limited the fire rate of the player’s lasers.
Our initial value of 0.5 seems pretty sluggish for a laser-shooting space ship, so we can increase the rate of fire by reducing the fire delay amount. We can do this in the Unity editor since we chose to serialize the field, or we can adjust the value in the code if we want to lower our default fire rate.
The value of 0.15 gives us a much faster fire rate that feels more appropriate and fun.
There we have it! We’ve limited our player’s fire rate by implementing a cooldown system on our fire ability. Tomorrow we’ll look at an introduction to physics in Unity! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.