Performance: Why coroutines handle time-based logic
This affects how smoothly time-based actions run without blocking the main game loop, impacting frame rate and responsiveness.
IEnumerator WaitAndDo() {
yield return new WaitForSeconds(delay);
// continue logic
}
void Start() {
StartCoroutine(WaitAndDo());
}void Update() {
if (Time.time < startTime + delay) {
// busy wait, do nothing
} else {
// continue logic
}
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Busy wait in Update loop | N/A | Blocks frame updates | Causes frame drops | [X] Bad |
| Coroutine with WaitForSeconds | N/A | No blocking | Smooth frame rendering | [OK] Good |
IEnumerator PrintNumbers()
{
for (int i = 1; i <= 3; i++)
{
Debug.Log(i);
yield return new WaitForSeconds(1);
}
}
StartCoroutine(PrintNumbers());IEnumerator WaitAndPrint()
{
Debug.Log("Start");
WaitForSeconds(2);
Debug.Log("End");
}
StartCoroutine(WaitAndPrint());IEnumerator BlinkLight()
{
while(true)
{
light.enabled = !light.enabled;
// What goes here?
}
}Pass the test and this pattern moves unknown