Below is a simple example of the difference I would like to highlight.
Using coroutines:
public float repeatRate = 5f;
void Start()
{
StartCoroutine("RepeatSomething");
}
IEnumerator RepeatSomething()
{
while (true)
{
yield return new WaitForSeconds(repeatRate);
// Do something
}
}
Using Update()
and Time.deltaTime
:
public float repeatRate = 5f;
private float timer = 0;
void Update()
{
if (timer < 0)
{
// Do something
timer = repeatRate;
}
timer -= Time.deltaTime;
}
When should I use one as opposed to the other and what are the advantages/disadvantages of each?
In most cases the answer would be.
In general the performance difference between Update and Coroutine is not relevant. Just follow the approach that suits you best, but use the much more performant MEC Coroutines
instead of Unity Coroutine
if you want to follow a Coroutine-like approach.
MEC Coroutine
performance analysis. Unity Coroutine
performance analysis.As mentioned in the unity forum in general "Coroutines
are useful for executing methods over a number of frames [and then forget about it]."
If you plan to use just a few of them (less than 10k?), then you're fine also with Unity Coroutines
.
At the moment Unity supports Task/Async, but the performance is still quite low. So you might think about using Coroutines
to simulate Async
functionality.
In this case you might even use Coroutines
to remove all (or most of) your Update
loops, such as in the example you posted.
This is useful in terms of performance, especially in your specific case, because when you use the Update
loop you keep costantly checking for the if (timer < 0)
even when you're doing nothing. And even an empty Update Loop is still a performance issue.
On the other hand you might just start and stop Coroutines
when an event happens. And when the Coroutine stops the performance cost becomes 0.
If you want to follow this method I strongly suggest to use MEC coroutines that removes all the performance issues caused by Unity Coroutines (and have the same functionality).
MEC Coroutines
are a bit more performant than the Update loopUpdate
loop is generally more performant than Unity Coroutines
Unity Coroutines
should be used only for simple timed tasks that happens rarelyPS: this answer about unity coroutine might help you understanding how they work in depth.
PPS: this old answer might give you further insight, but it is a bit outdated, especially when it talks about the garbage collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With