Unity Coding — Cooldown
If you have played or watched someone play a video game even once in your life, you have most likely seen what is commonly referred to as “button mashing.” This is when players don’t reeeaaaally know what they are doing and just hit the buttons as fast as they possibly can. As a developer, you might want to put some things in place to make sure this is not an optimal strategy.
For this example, let’s look at a small prototype where cube represents the player and the smaller blue capsules are the projectiles. The player can shoot a projectile by pressing Spacebar. Let’s look at what happens when there is nothing in place to slow this down.
Seems a bit much doesn’t it? So let’s put something in place to slow this down regardless of how fast the players mash that Spacebar. In games this is called a cooldown. While in our example, it will only be a fraction of a second, cooldowns are more commonly referred to when using powerful spells in RPGs. So let’s say right now our shooting code looks like this:
Every time Spacebar is pressing, a new capsule or laser will be instantiated. In that IF statement, we can add another condition to change this. This condition should be based on time. How much time should pass between being able to fire? I will be using 0.15 of a second, but you can play around with any number you want. So let’s make a variable holding that number.
In Unity, there is something called Time.time. Time.time is the actual time that passed since a Scene has begun. If you ran it 2 minutes ago, it would 120 seconds. So if you want to make a cooldown that works continuously throughout the scene, you can use Time.time and your fireRate variable to figure out the cooldown. Once you fire a projectile, the next time you fire should always be the current Time.time plus that fireRate.
Place this number into another float variable and reset it every time the player places Spacebar.
Finally, add the condition to the IF statement, that way it does its purpose and prevents lasers to shoot if the proper time has not passed.
Now let’s see how that looks.
Seems much more reasonable now. Take this knowledge with you and put a stop to those wild button mashers.