Creating a Cooldown System in Unity!
Personally, I enjoy being able to spam the space key and shoot lasers out of the player as fast as possible. To shoot the top of the screen more times than Murphy at the beginning of RoboCop. However, much like the movie, in a shooting game that’s not realistic. So, much to my chagrin, we need to ass a cooldown system to prevent ourselves from being able to spam the fire button.
Open the player script. We need to add a logic that can tell how much time passed to the input code. For the sake of this tutorial, we are going to us 0.5 seconds for the cooldown. Now let’s make this into a usable variable.
For this to work we must use a format Time.time. Time.time is the conscept of passing time. This will always track the amount of time that has passed since the game started in seconds, and that amount will represent the value of time.time. If the game has run for 5 minutes it’s value will be 300, if the game has run for 2 minutes the Time.time will be a value of 120.
Now we need one more variable, we will call this one canFire.
We can now add these variables into you input code.
This formula will now control the rate of fire. The formula is if Time.time is larger than _canFire you can shoot the laser.
If Time.time is 1 that would mean the can fire is 1 + 0.5 = 1.5. So, the Time.time won’t be larger for another half a second. If this is too slow for you can always turn down the _fireRate to shoot faster. Try 0.2, that feels good to me.
Now the player is ready to defend himself against whatever enemies we build to attack him, or is he? We will find out on the next tutorial when we start working on enemies and physics.