- Home /
What's the most efficient way to time events?
Up until now, whenever I needed to time something like an animation or the rate at which enemies spawn in a game I would use an integer variable to which I would add 1 on the update function. When that number reached a certain amount (say 120 if I wanted a 2 seconds delay), It would activate whatever needed to be activated.
It does, however, feel like a really primitive method, and I'm wondering what is usually used for timing events. Also, would changing the method affect performance?
Answer by christoph_r · Aug 14, 2014 at 02:07 PM
Yes, it's usually a good idea to do as little as possible in Update, usually only checking for user input. There are generally two ways to time code: Coroutines and using Invoke. Especially if you're new, coroutines can take some effort to get into, Invoke is usually the easier method. Of course both of those are much more performance-friendly than changing a value in Update, even though if it's not thousands of scripts doing that, it shouldn't be a big issue either. What can be an issue, though, is that not all frames last the same amount of time, so if you ever need to use that method again, make sure to use FixedUpdate. Again, though, coroutines and Invoke are far superior.
Answer by MrSteve1 · Aug 14, 2014 at 02:05 PM
essentially the opposite of your current way to be honest. Typically my countdown timers tend to look like this.
var timer : float = 20;
function Update()
{
timer -= Time.deltaTime;
if(timer < 0)
{
doSomeCoolStuff();
timer = 20;
}
}
function doSomeCoolStuff()
{
print("Hello World");
}
and then I would evolve from there.
Hope this helps!
This is fine for repeating events that must continue to occur as long as the script is enabled. But checking a counter value in Update for one-off events is inelegant because Update will continue to check the variable over and over again even though it reached 0 a long time ago.
The coroutine is the established way to trigger timed events, and are an often-used code mechanic in Unity3D. You're better off learning them sooner rather than later, and applying them for this purpose. It will give you cleaner, more efficient code.