Creating & Using Cooldown Functions

Kenny Pruitt
Unity Coder Corner
Published in
3 min readFeb 26, 2023

Objective: Add A Fire Rate For The Laser

To make a fire rate for our laser, we basically need to add a cooldown function that prevents us from shooting as fast as we can press the button to shoot. To do this we can create a bool function that checks to see if our cooldown time has passed and if so return a true or false statement. We can do so like the picture below.

When creating a function that needs to return a variable, you must always add a default return value in case your function parameters are not reached. To do so, we can simply make this return false by default, because we only want it to return true if the cooldown for the button pressed has passed.

Now we can start creating our parameters for a cooldown. To make a cooldown there are a few things needed such as how long the cooldown timer should be run for, represented by fireRate. Your actual cooldown timer that is being monitored, represented by fireRateCooldown. And finally a bool that tells the function to set the fireRateCooldown to the fireRate.

Next we need a way to decrease the cooldown timer over time until it reaches 0. To do so we can simply say if the fireRateCooldown is greater than 0 then subtract the fireRateCooldown from Time.deltaTime.

If the fireRateCooldown is less than or equal to 0 then our statement can return a true statement and we will be able to fire the laser again.

Now that we have our cooldown function all setup, all we need to do, is in the FireLaser function, just add the bool setFireCooldown and set it to true so that the cooldown function will start over.

Now we have control over our rate of fire in Unity. We just need to set our desired Fire Rate in the inspector window for our player.

--

--

Kenny Pruitt
Unity Coder Corner

Unity Game Developer, C# Developer, and Software Engineer