Day 10: Creating A Cooldown System in Unity
Objective: Create a cool down so we can’t spam firing.
Here we will be using a Coroutine to handle the cool down as well as using a bool. To start off we will need a bool to see if we can fire.
We set it to true at the beginning so we can fire at least once before the cool down starts. Now that we have a bool, we need to check for that when we fire.
Now that we check it, we can still spam space to fire, next will be to set it false so we can’t fire again.
Now since we fired, we wont be able to fire again. The reason is that the bool never gets set back to true. Here we will start the Coroutine.
When we start a Coroutine, we will need a IEnumerator function to run, here we called it LaserCoolDown().
Here we created the IEnumerator LaserCoolDown(). For this function not to give an error, you will need a yield return. Here we did yield return new WaitForSeconds(laserCoolDown). This will be put on hold for what laserCoolDown is set to. We don’t need to have a variable here but I wanted to control this in the inspector.
After the time in seconds is up, the bool _canLaserFire will be set to true again. Now we have a working cool down system!
To make the code look a little more clean we can pull all the code out into it’s own function.