Without some time limit between shots, a player can just spam the fire button, creating a “wall” of projectiles. (Actually, that sounds pretty cool; maybe we’ll make a power-up that allows that!)
Making a cooldown system in Unity is pretty easy. We need two variables: One to set how often we can fire (_fireRate), and another to track the next time we’re allowed to take a shot (_nextFire). We’ll make the fire rate serializable so the game designers on our team can set it however they’d like in the inspector. We’ll initialize _nextFire as 0 so the player can fire their first shot as soon as the game starts.
When the player presses the fire button (in this case the spacebar), we’ll check to see if Time.time — that is, the time since the game started — is greater than or equal to the time the next shot is allowed (_nextFire). If it is, we’ll let the player shoot. If not, they’ve fatigued their poor button-pressing finger for naught. (Really, who talks like that?)
If the shot was allowed, we add the fire rate to the current game time (Time.time) and assign that as the next time the player is allowed to fire.
Here’s the final result:
I’m sure if you put your mind to it, you can think of other ways to use a cooldown system. Play your favorite video game and try to find the places the developers implemented a cooldown timer. If you’re as much of a nerd as I am, when you’re playing game, you’ll think, “how did they do that?”