Creating a Cooldown on How Quickly the Player Can Fire

David Hunter Thornton
3 min readAug 13, 2022

--

How do I prevent the player from spamming a button?

Objective: Explain the system for forcing the spawn rate to wait despite a player having pressed the appropriate key again.

At the moment in this series, we have a Player Character that can fire bullets as quickly as the user can spam the button. In order to prevent this, we’re going to discuss the basics of Coroutines and IEnumerators.

This is closer to intermediate level programming than beginner but its less performance heavy than some simpler options. Coroutines run a check once a second, where as most other functions or methods are added to “void Update()” and run every frame.

Before we get too far though, let’s start by making a simple “bool” variable to find out if our bullet can even be fired. It’s worth noting, that a bool by default is set to “false”. So we need to declare it as “true” for this.

Now we want to head down to our “Fire1” input section. Here we are going to use a logic operator “&&”. This will only check the second condition if the first condition is true. So for us “if the ‘Fire1’ button is pressed and ‘_bulletCanFire’ is true”. But instead of constantly checking if “_bulletCanFire” is true, it’ll only check when the ‘Fire1’ button is pressed. And it’ll only initiate our code if both are true.

Now we need to add two things beneath this in the actionable code for when both things are true. At the moment we only have our object spawning at an offset. The best thing is we can just start a new line of code underneath that one, and it’ll initiate our code in order one at a time.

We set the bullet can fire to false because the user just pressed the button. So we’re going to change the state to false until a timer has finished. This is where our Coroutine actually comes into play.

With the StartCoroutine command done, we also need to actually make the Coroutine method.

IEnumerator simply labels our method/function as a Coroutine, followed by whatever we’d like to name our method/function. It’s important to note, that the yield callout is required to return information. And since we want to call a new “WaitForSeconds” we’ll need it.

As the final cherry on our “Cooldown Sunday” we tell the Coroutine, “once you’re done counting to 0.5 seconds, return ‘_bulletCanFire’ to the true state”. And we now have limited how often the user can fire a bullet! Hopefully this wasn’t too complicated, but if you still have questions, don’t forget to check your Scripting API for more information.

Friendly Reminder: Don’t forget to keep updating your project through GitHub/Git and saving any changes you make to a separate branch. You can check out my other articles to get a breakdown of those steps! Day 1–9

--

--