Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Unity, when should I use coroutines versus subtracting Time.deltaTime in Update()?

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?

like image 564
Roger Wang Avatar asked Feb 03 '23 15:02

Roger Wang


1 Answers

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.

SIMPLE USAGE

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.

ADVANCED USAGE

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).


IN CONCLUSION

  1. In most situation this difference of performance is not relevant
  2. MEC Coroutines are a bit more performant than the Update loop
  3. Update loop is generally more performant than Unity Coroutines
  4. Unity Coroutines should be used only for simple timed tasks that happens rarely

PS: 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.

like image 77
Jack Mariani Avatar answered Feb 06 '23 11:02

Jack Mariani