Creating A Cooldown System in Unity

Joe

--

As it stands now the lasers shoot out as fast as the player can hammer the fire key. After switching the fire input to using the “Fire1” key from the input manager and assigning it to the space key, if that key is held down a constant stream of lasers fire out. This of course is not the behavior that is wanted.

Lasers with no cooldown

Two new variables will need to be defined so that the laser firing can be tracked. Lets define them as

Cooldown variable declarations

The first variable _fireRate determines the interval that the lasers can fire. It is currently assigned to be able to fire every .2 seconds.

The second variable _canFire is added to the current time of the game to generate the value to check if the _fireRate time has passed.

This check is done by using Time.time which is the time in seconds since the start of the application.

So if Time.time is added to the _fireRate then the _canFire value can be checked to see if the correct amount of time has passed to allow another laser to fire.

Using our existing if statement and checking for both the fireButton and Time.time > _canFire we can establish whether the laser can fire again. Inside the if statement _canfire will need to be recalculated by adding _fireRate to the current Time.time value. This all looks like the following when put together.

Updated firing mechanism to implement cooldown
Controlled laser fire with cooldown implemented

This not only provides a controlled rate of fire but also a way to increase or decrease the rate of fire at a later point in the game.

--

--