Creating a Cooldown System in Unity

Andrew Crippen
3 min readApr 15, 2021

--

Lasers firing as fast as you can press the button before the cooldown system is implemented

In this guide I will show how to implement an easy cooldown system, it’s good for controlling the rate of fire so that a player can’t just spam the fire button. The same method can be used for pretty much anything that relies on waiting a set amount of time before input is allowed to actually do anything.

This is how my firing of laser is handled in my Player script before the cooldown system is implemented…

We need to be able to tell how much time has passed so we’ll use Time.time

The Unity script reference describes Time.time as the time in seconds since the start of the application/game.

Now that we know how much time has passed since the start of the game we need a variable to see if enough time has passed to be able to fire again, which I will name _canFire and set it’s initial value to -1f so that it works at the start of the game.

We also need a variable for our fire rate or fire delay however you want to word it. I’ll use half of a second for the example here. I also serialize the field so that it can be modified in the inspector. I use _fireRate for the name of this variable and set it’s value to 0.5f

Now each time we fire we need it to set the value of _canFire. We’ll add Time.time to the _fireRate to create the new value of _canFire

Now each time the fire button is pressed we need it to check if Time.time is greater than _canFire . The double ampersand && is used to make it meet both conditions before it will run the code within the brackets.

Now each time the fire button is pressed it will check to see if the current time is more than the current time was plus the fire rate/ fire delay. If it is then it will set the new value for _canFire and fire a laser.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Andrew Crippen
Andrew Crippen

Written by Andrew Crippen

Unity Developer/C# Programmer for VR, 2d,3d Games and other Immersive Interactive Experiences

No responses yet

Write a response