Journal 08 — Time for a Cooldown in Unity

In the previous Journal, I mentioned a need to briefly pause when firing lasers, so the user cannot just spam the spacebar endlessly.

Unity Playmode — SPAM THE SPACEBAR!

Sort of unfair, right?

In the Player C# script, when pressing the spacebar, we have added a cooldown condition.

Unity C# cooldown for firing laser prefabs

&& — means AND, so pressing the spacebar and the other condition must be met before being able to fire. In this example, time in seconds must be greater than the user set time delay before the next laser prefab can be instantiated

Time.time — count real time in seconds

_nextFire — a calculation that adds Time.time to a user set time delay between firing

Unity C# fire laser function and time delay

Let’s see how this works:

Unity Playmode with time delay on while firing laser prefabs

Seems more fair. If you wanted to, you could add a powerup later that would turn off any delay, or possibly turn on auto-fire by holding the spacebar for a few seconds.

I appreciate you stopping by. I look forward to share more info as I gain experience with Unity and C#.

Thanks!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chris Nielsen

Chris Nielsen

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.