Creating timers in Unity

One of the most common things to do in game programming is to wait for a certain period of time before calling an event. In this article you will find several types of timers in Unity explained and when to use them.

Simple repeating timer in Update()

Let’s create the most basic timer that does something every x seconds:

  • waitTime means how long to wait in between action calls and can be overriden via the inspector.
  • timer is used to store the time that has passed.
  • Update() is called every frame, so we add our deltaTime to our timer in every Update() cycle. The property deltaTime returns how much time in seconds has passed since the last frame.
  • If our timer has risen above our waiting time, a method is called.
  • In place of the print() statement, you can call whatever action needs to repeat.
  • We restart the timer by resetting it to zero.

 

DeltaTime in Unity.
DeltaTime in Unity.

 

DeltaTime in Unity gives us the length of the previous frame, which if you’re running at 60 fps is 1/60 of a second, or about 0.016 seconds.

The basic timer shown above is easy and fast, but your code might end up being cluttered, because the timer is not sealed off in it’s own method.

Here’s another example, that can be turned on and off:

Toggle timer via Update()

 

First, OnTriggerEnter() is called, whenever our CannonBall enters the trigger area  of any GameObject tagged “Player”. This sets the boolean timerRunning true.

The Update() loop is checking every frame for timerRunning and when it becomes true, it calls the BombTimer method. Our timer waits for waitTime to pass and then does something.

Lastly, the timer resets itself until another Player trigger is entered.

Unity offers a few helper functions that can call methods after a period a time or repeat actions:

Destroy an object after x seconds

You can use the Destroy() method from MonoBehaviour and pass in a float parameter to delay it. Note, that you only want to call this method once, not in Update().

Invoking a method after x seconds or repeating it

The Invoke() method takes a method name as a string and the waitTime as a float parameter. This helper function is very convenient, because of it’s clean syntax, but be aware, that invoking methods via string is much slower than calling them directly. Only use this for testing or when performance isn’t an issue.

You can also use InvokeRepeating() to wait for a period of time and then repeat the method call every x seconds:

Again, the Invoke() methods are convenient but slow.

You can stop the Invoke() or InvokeRepeating() method by using CancelInvoke(“MethodName”).

Waiting timer in a Coroutine

Coroutines are incredibly cool and we can use them to create well-performing timers with clean syntax. A coroutine has the ability to pause and resume itself while running in your game.

Pay attention to the using statement that includes System.Collections; we need this to be able to use coroutines.

A coroutine returns a type of IEnumerator. It is not necessary to fully understand what this means, because we’re not making use of the return type with our timer.

Inside of a coroutine, you can pause it’s execution with the yield statement. The yield can return, for example, the WaitForSeconds() method, which waits for any number of seconds passed into it before continuing execution.

Be aware, that a coroutine must include at least one yield statement. If you do not want to wait for several seconds, you can yield return null to wait until the end of the frame like any standard method does. In this example, we could omit this last step, since we we’re already yielding earlier, but just for completeness, I included it.

To start a coroutine, use StartCoroutine() and be aware, that you should pass in a method call as a parameter, as it is much faster than using a string.

Repeating timer via recursive coroutine

This heading sounds complicated, but it actually isn’t. Just look at the code:

Only one line was added to make our coroutine repeat every three seconds. In line 17 HarmPlayer() calls itself, which is known as a recursive method call.

Many times, recursive methods can get very complicated and cause hard-to-understand problems, but in our case they work nice and easy: The method waits for a period of time, then performs the print() statement and finally calls itself again, therefore repeating the timer.

You can stop a coroutine with StopCoroutine(methodName ()) or cancel all running coroutines with StopAllCoroutines().

When to use coroutines over Update()

As you might be thinking, coroutines can replace your Update() loop. I suggest to use them whenever you need time-based functionality, but you want to keep your Update() clutter free.

Coroutines are ideal for timers, moving objects via script or lerping between values.

*lerping refers to Linear Interpolation. See the official Unity tutorial for more information.

 

Please leave me a comment, if you’d like to see more practical examples of timers or if you have any more questions.

 

Published by

Chris Yarbrough

Game Design student at Mediadesign Hochschule, Munich.

Leave a Reply