Creating a cooldown system in Unity
Objective: Create a cooldown system to control how often lasers can fire
In the previous post a laser prefab and script were created along with the logic for the player to shoot lasers. The lasers shoot infinitely and with no restrictions on how fast each shot can be.
Objective: To create a cooldown system to allow a specific amount of time to pass between when the player shoots a laser to when they can shoot the next laser regardless of how fast or how many times the fire key is pressed.
We start by creating a fireRate variable within the Player script. This will be the amount of time between firing the laser to when we can fire again. Create the private float and serialize it to allow editor manipulation and set the value to 0.5f.
When using game time or play time (how long the game has been running) we use Time.time. This clock will run per second so if the game has been running for two minutes, Time.time will be 120.
Next we can create a nextFire variable which will be set to the next time we are allowed to fire. The initial value will be set to 0f meaning we are allowed our first shot instantly. Create a new private float called nextFire and set the value. As usual this will be serialized to allow for editor manipulation.
Now that the nextFire is set, the next thing is to modify the laser shooting logic to test for passed time. If next fire is ready then shoot a laser and modify the next fire value using Time.time and fireRate to set the nextFire value. Our new nextFire value will be set as Time.time(the current game time or how long the game has been running until this second and the fireRate value).
This may seem a little slow but all that is needed is to modify the fireRate valuable(currently 0.5f) to something like 0.2f instead. Not too fast as later, powerups like rapid fire, triple fire and more will be added to the game.
In the next post, we’ll look at some Unity Physics.