As fun as shooting at the speed of light can be, it can turn the player into an overpowered monster and limit the challenge of an experience. Cooldown systems exist to limit firerates of weapons, set delays on abilities, respawn timers, and more!
In our case, we want to limit the player’s ability to spam out lasers from as fast as they can press the spacebar to every half second.
We want to limit the instantiation of the lasers, so these edits will go to where we instantiate the laser; the player script.
Add two new float variables; fireRate and nextFire. You can set their values to whatever times you like, but nextFire must be lower in value than fireRate, or the system won’t work!
Now we can add to the FireLaser method from my earlier articles to get the desired behavior.
We check nextFire vs Time.time (which is how long the game has been running)
Now, we need to set the cooldown period inside the “if” statement.
So in order to get this function to fire, nextfire has to be a lower value than Time.time, and we must press the spacebar.
When we do, the nextFire variable becomes Time.time + the fireRate value.
Therefore, we must wait the fireRate value before the “if” statment conditional is true again, and we can fire again.
And that’s it! this can be repurposed to make ability cooldowns, can be extended for different weapon types, etc.