Cool Down System

Austin Hall
3 min readAug 31, 2022

--

where does it make sense to implement a cool down system? Well… the cool down system is related to our firing method so we will be inside our Player script and in the block of code that instantiates the laser when the space bar is pressed.

Player script inside the If statement within the Update() method

We want to limit the fire rate. We’ll need to set the rate, identify when the opportunity to fire happens and do this real time. For this we will need two variables (see below)

The function Time.time will allow us to pass time during the operation. If we do a quick internet search for Time.time, we can find the unity scripting API for this function.

Internet search for Unity function and accessing Unity API

In the Unity scripting API, it actually gives us an example for a cool down system.

Snippet from Unity API Time.time function

Looking at the example from the API, we see 2 variables and the use of Time.time. Let’s implement this function into our code and look at the logic.

Snippet from Unity Player script

Logically speaking, this code reads… if the space key is pressed down AND the passing time is greater than the value of _nextFire, execute the folling if statement. So the following block of code only runs if _nextFire is less than time and the spacebar is pressed.

When executed, _nextFire will be assigned a new value equal to time plus the value of _fireRate and the laser will be instantiated one time. This will not happen again until the passing time is greater than the new value of _nextFire.

For example, _nexFire is set to 0 and the passing time is at 1. One is greater than zero. So when the space key is pressed the If statement executes. Now, _nextFire is set to 1(time) plus .5(_fireRate). Time moves to 1.1 and we check the if statement again. This time, Time.time is 1.1 and _nextFire is 1.5. So the if statement will not exicute again until time reaches 1.6, giving us a fire delay or cool down.

Lastly, I will clean up my code. I need to remove any unnecessary comments and pseudo code. Also, to help myself down the road, I am going to make a function called FireLaser(). The code for pressing the spacebar and instantiating the laser will go here. The if statement that compares time to nextFire will stay in the Update() function.

Revised Update() function
New function for firing the laser

--

--