Cooldown Systems
Objective: Implement a cooldown system for player laser fire.
Cooldown systems are variables that prohibit an action until a timer expires. For a cooldown system to work two float variables are required: the duration of the cooldown, _fireRate, and another for the time when the cooldown expires, _canFire.
The logic is as follows: if the space bar is pressed and Time.time, which is the time when the frame starts, is greater than the _canFire value then call FireWeapons(). In the FireWeapons() method we set the _canFire timer to the current time plus the cooldown _fireRate then Instantiate the laser pulse. Initially _canFire is the default, 0, and the laser can be fired at frame with a start time of 0.02 s. Once fired _canFire jumps from 0 to 0.27. If the frame rate is 50 Hz then it will take 13 frames before Time.time is large enough to enable a laser pulse to fire again.
Why not use use an IEnumerator method for FireWeapons() with a yield return new WaitForSeconds(_fireRate) as shown below? The problem for a laser cooldown system is that void Update is monitoring for the fire event every frame and restarts the IEnumerator method every frame. The yield statement is never completed because void Update restarts the coroutine before the timer expires.