My 120-day journey to being a better Unity Developer — Day 9

Creating A Cooldown System in Unity

Implementing a cooldown system (right)

Objective: Add a cooldown system to limit how fast the player can fire the lasers.

As you can see above, the player on the left has a far better advantage of shooting down the enemies. We need to control the amount of time between each shot. Let's create a fire rate that we can adjust in the Inspector:

We also need a _canFire variable that stores the fire rate plus the last time it was fired. Each time it fires, we reset the next time it can fire by adding the current time to the fire rate.

Now, when we detect the space key has been pressed, we check if the _canFire time is less than the current time, Time.time, if it is, we can fire again.

In the Inspector, we can adjust the Fire Rate making it easy for our Game Designer on the team to find the right firing rate.

Our Game Designer has found a bug where they can choose a negative value. Let's fix this by doing two things, make the control more user-friendly with a slider control and help make our design process less prone to user errors. We do this using the Range attribute.

We have a cooldown system implemented that can easily be changed by the game designers on our team to get the right ‘feel’.

Final Code:

If you enjoyed reading this article, and you want to see more like this, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com