Performance: Coroutine chaining
Coroutine chaining affects frame rendering and responsiveness by controlling how asynchronous tasks run over multiple frames.
IEnumerator GoodChain() {
yield return StartCoroutine(Task1());
yield return StartCoroutine(Task2Async());
yield return StartCoroutine(Task3());
}
IEnumerator Task2Async() {
for(int i=0; i<1000000; i++) {
if(i % 10000 == 0) yield return null; // spread work over frames
}
}IEnumerator BadChain() {
yield return StartCoroutine(Task1());
Task2(); // Runs synchronously, blocking frame
yield return StartCoroutine(Task3());
}
void Task2() {
// Heavy synchronous work
for(int i=0; i<1000000; i++) { /* heavy work */ }
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous heavy task in coroutine chain | N/A | Blocks main thread | Causes frame drops | [X] Bad |
| Asynchronous chunked task with yield return | N/A | Non-blocking | Smooth frame updates | [OK] Good |
yield return StartCoroutine() do in Unity coroutine chaining?yield return StartCoroutine()First() and Second() in Unity?IEnumerator First() {
Debug.Log("Start First");
yield return new WaitForSeconds(1);
Debug.Log("End First");
}
IEnumerator Second() {
Debug.Log("Start Second");
yield return new WaitForSeconds(1);
Debug.Log("End Second");
}
IEnumerator Chain() {
yield return StartCoroutine(First());
yield return StartCoroutine(Second());
Debug.Log("Chain Complete");
}IEnumerator Chain() {
StartCoroutine(First());
yield return StartCoroutine(Second());
Debug.Log("Done");
}LoadData(), ProcessData(), and DisplayData() so each starts only after the previous finishes. Which code snippet correctly implements this chaining?Pass the test and this pattern moves unknown