Creating a Cooldown System in Unity
Slowing Down the Firing Power
In my sample 2D Space Shooter game, the ability to constantly fire a laser as fast as I could press the keyboard was not what I wanted.
In order to change this, I had to implement a Cooldown System.
The first thing I did, was look at my “Player” script. I needed to add some time logic to my code to let the system know how much time had passed.
- In my “Player” script, I created a private float variable named _fireRate and assigned a value of 0.5f. I used the [SerializeField] attribute so it can be changed while in game testing, just to make sure 0.5f was going to work. I then created another private float variable named _canFire with a value of -1f, which will be used to calculate the time passed.
[SerializeField]
private float _fireRate = 0.5f;
private float _canFire = -1f;
Next, I had to add some more code to the “Player” script to implement the time constraint on the rate of fire. I used “Time.time” to get the amount of time the game has been running.
Now, I can calculate what time in the game the player pressed the fire button and assign a new value to that time. Then I check the difference to see if 0.5 seconds have passed. If it has, the player can fire again. If it hasn’t, the player will have to wait until the system shows 0.5 seconds have passed. The code is written in the “Player” script inside the method used to get the key input and GameObject Instantiation.
if (Input.GetKeyDown(KeyCode.Space) && Time.time > _canFire)
{
_canFire = Time.time + _fireRate;
Instantiate(_laserPrefab, transform.position + new Vector3(0, 0.85f, 0), Quaternion.identity);
}
Now, the firing is more controlled. There is a cooldown after each firing.