IEnumerator and yield
- Game Development course
- Intermediate
- Lesson 44/83
- 4 min
Learn to use IEnumerator and yield return null.
IEnumerator and yield return null
For Unity to recognize a method as a coroutine, it must return the IEnumerator interface from System.Collections and contain at least one yield statement in its body.
using System.Collections;
IEnumerator StepRoutine() {
// Wait for one frame
yield return null;
}The yield return null; instruction tells Unity that the current frame is yielded and execution must resume on the very next frame.
Early exit with yield break
When a specific condition requires terminating a running coroutine early, yield break; is invoked. Operating much like return; in regular methods, it shuts down the coroutine entirely.
IEnumerator HealthMonitor(int hp) {
if (hp <= 0) {
yield break; // Halts coroutine when health is depleted
}
yield return null;
}This prevents superfluous iteration cycles and maintains performance optimization.
Practice Print return and yield state
Assign "IEnumerator" to returnType and "null" to yieldState. Print Return: IEnumerator | Yield: null to the console.
Starter code
using System;
class Program
{
static void Main()
{
// returnType ve yieldState değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string returnType = "IEnumerator";
string yieldState = "null";
Console.WriteLine("Return: " + returnType + " | Yield: " + yieldState);
}
}Expected output
Return: IEnumerator | Yield: null
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is written inside a coroutine to wait precisely until the next frame?
- return 0;
- yield break;
- Thread.Sleep(1000);
- yield return null; Correct answer
Explanation: yield return null is the standard statement that pauses the coroutine until the following frame.
2 Yield until next frame
yield return ____;
yield return null;
Explanation: The expression yield return null is used to wait for one frame.
3 IEnumerator and yield terms
| Term | Meaning |
|---|---|
IEnumerator |
Coroutine mandatory return type |
yield return null |
Wait until next frame |
yield break |
End coroutine execution now |
System.Collections |
Namespace holding IEnumerator |