Controlling how your player plays your game is very important in any game. As a game developer or game designer, your ability to make a player wait to reload a gun or missile is key to compelling gameplay. Called a Cooldown system, I will outline how to create one for your games in this article.
Time is critical
The basis of any Cooldown system is Time and Unity provides a class called Time with many available Static Properties. For our Cooldown system, we use Time.time, which is the time in seconds from when the game was started. This information is critical to our Cooldown system.
The first part of your Cooldown system is to determine how quickly you want the player to fire and the initial value before they can fire. So, we create two variables
private float _fireRate = value;private float _canFire = value;
You can SerializeField these variables to be able to modify and test them in the Inspector.
Time after Time
With the variables in place, we now use them in a simple formula with Time.time (actual game time).
_canFire = Time.time + _firerate
Here we are updating the value of _canFire with the actual game time added to the predefined fire rate. It is updated every time the weapon is fired before the GameObject is Instantiated.
Can I fire now
To determine if the weapon can be fired in the condition statement, we check to see if the actual game time is greater than the _canFire variable. If the conditions are met, the weapon can be fired by the player.
if (Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
_canFire = Time.time + _fireRate;
Instantiate(Prefab, position, rotation);
Here is an example of a completed script
I hope this article helps you create a Cooldown system for your next or current game. Good luck, and let me know if I can help.