I’m wondering what is more performance-effective - a yield in a Coroutine or a countdown in Update(). For example, for my random background sounds, I have two scripts - which one should I use, and which costs unnecessary performance?
C# - using Update() with countdown
using UnityEngine;
using System.Collections;
public class RandomSound : MonoBehaviour {
public float MinWait = 0.0f;
public float MaxWait = 10.0f;
private float Wait = 0.0f;
void Update () {
if (!audio.isPlaying) {
if (Wait<0.0f) {
audio.Play();
Wait = Random.Range(MinWait, MaxWait);
} else {
Wait-=Time.deltaTime;
}
}
}
}
or Javascript - using a Coroutine
var MinWait = 1.0;
var MaxWait = 10.0;
private var running : boolean = true;
yield RunSound();
function RunSound() {
while (running) {
var RandomWait = Random.Range(MinWait, MaxWait);
yield WaitForSeconds(RandomWait + audio.clip.length);
audio.Play();
}
}
If there even is a performance difference, it will not have any measurable effect on your game. In my opinion, you should pick the yield version. Coroutines make for much more readable code, especially for more complex combinations of events. Most of my scripts don’t even have an Update function anymore. That’s how big my love for Coroutines is ;).
Note: I don’t know why you mention the different languages, both languages can do both approaches just fine.
Perhaps one argument for not using the yield approach is that it isn’t standard practice in other languages, so if you are coming to Unity from something else it isn’t immediately obvious how it works.
Perhaps this is to the detriment of the other languages though
In this case you should indeed use yield for readability.
Regarding optimization, relying on the built-in delay system is always a good idea as that allows us to optimize when it makes sense. As mentioned, the difference will probably be negligible, but increasing with the delay size.
If you are going to use the Update method, be sure to disable the component when you are not using it.
I found a large speed increase on iPhone (10 fps) when I started managing the calling of Updates/using Coroutines as opposed to putting an if statement within the update (the update itself seemed to be somewhat slow to call).
Thats right, update or any of the callback functions are slow cause they are not called by objects from what it seems but through a SendMessage alike mechanism