In Unity you can use:
IEnumerator WaiterRoutine()
{
yield return new WaitForSeconds(<seconds as float>);
}
To wait a number of seconds. But this generates garbage for the garbage collector. I have a routine that waits for a random number of seconds every time it runs. So it just continually creates garbage.
My question is: is there any reason not to wait like this instead:
public static IEnumerator WaitForSeconds(float seconds)
{
float start = Time.time;
while (Time.time < start + seconds)
{
yield return null;
}
}
and if not, then why the heck is this not part of Unity's libraries? Is new WaitForSeconds somehow optimized further? Like does it remove my routine from consideration rather than busy waiting?
Just trying to figure out an efficient way to handle waiting.
Here's the actual code in question:
void OnEnable() => routine = StartCoroutine(SpiritCannon());
void OnDisable() => StopCoroutine(routine);
private IEnumerator SpiritCannon()
{
while (true)
{
yield return Helpers.WaitForSeconds(Random.Range(minWaitSecs, maxWaitSecs));
animancer.Play(spiritAnimation[animationCycler.Next()]);
}
}
yield return Helpers.WaitForSeconds(Random.Range(minWaitSecs, maxWaitSecs));
allocates garbage. It instantiates a new instance of a class created from your staticWaitForSeconds
method, which includes the memory where it storesstart
andseconds
. If you copy and paste the contents ofWaitForSeconds
into yourSpiritCannon
method instead of callingWaitForSeconds
to start a new iterator, that would avoid that allocation. \$\endgroup\$