Based on these two threads on Unity Forums and my research on my final project I just tried to get my async scripts memory footprint down to nearly zero (3 Byte per Frame?) which is impossible with Unitys Coroutines because they are generating 17 Byte per Frame with just a single yield return null;
so I came up with a working solution generating zero garbage and providing access to simple delays (WaitForSeconds
).
public class GarbageFreeRoutine
{
private IEnumerator enumerator;
private float timer = 0;
private float waitTime = 0;
public GarbageFreeRoutine(IEnumerator enumerator)
{
this.enumerator = enumerator;
}
public void Update()
{
if (enumerator != null && (timer += Time.deltaTime) > waitTime && enumerator.MoveNext())
{
timer = 0;
object current = enumerator.Current;
if (current is float)
waitTime = (float)current;
else
waitTime = 0;
}
}
}
Default delay (one frame): yield return null
Delay of 5 Seconds: yield return 5f;
Usage:
GarbageFreeRoutine asyncRoutine;
void Start()
{
asyncroutine = new GarbageFreeRoutine(AsyncMethod());
}
void Update()
{
asyncRoutine.Update();
}
IEnumerator AsyncMethod()
{
for (;;)
{
yield return null;
}
}
Hope I could reduce someone's memory footprint with this solution. Sometime it's annoying to see that Unitys solutions are creating masses of garbage (Coroutine on 25 objects, generating 17 Byte per Frame, 425 Byte per Frame, triggering GC every ~4 frames due to reaching GC threshold of 1 KiB).