Day 8: Creating a Cool Down System

Jonathan Fagan
3 min readDec 7, 2022

--

Objective: How to manage our fire rate system.

As we continue our Space Shooter Game we need to fix something before we move on to our next task which would be enemies. We need to fix our fire rate for the laser.

This is me pressing the space bar as fast as I can. If I wanted to go the route of fire one laser per shot.

And this is me if I wanted to fire a laser for every frame I hold the fire button.

It does look kinda cool though but nah

So let’s fix this. I will be using a coroutine to handle this problem. A coroutine allows you to spread tasks across several frames. In Unity, a coroutine is a method that can pause execution and return control to Unity but then continue where it left off on the following frame. And this will allow us to some special things.

So lets start by creating a coroutine variable using the Keyword Coroutine

Next we will assign a coroutine with all of our logic in it like this.

So to explain what’s going on. We created our coroutine with the IEnumerator Keyword and name it fireRate with an argument of a float type named rateOfFire. The argument will come in handy in a couple of lines. Next we call the function we made earlier called FireLaser and use a special keyword called yield. The yield keyword will pause the coroutine until what ever comes after it completely evaluates itself. In this case we are using “return new waitForSeconds(rateOfFire)”. This will wait for however long the rateOfFire is set to before giving control back to Unity and continuing to run the program. In which case we set _fireRate to null.

So here is where the magic happens.

In this piece of code where check to see on every frame if the Space key is held down. Then we check if the coroutine _fireRate is null. Which by default was set to null when we initialized it. If it is null we assign it to start the coroutine fireRate and pass in a _fireSpeed variable which we can adjust. And this is the outcome of all of our hard work.

Hope this helps. Happy Dev’Ing.

--

--