Why coroutines inherit from IEnumerator?

Viewed 142

How does inheriting from IEnumerator make the method to behave like a coroutine? This has to be somewhat related to the compiler, right?

IEnumerator Fade() 
{
    for (float ft = 1f; ft >= 0; ft -= 0.1f) 
    {
        Color c = renderer.material.color;
        c.a = ft;
        renderer.material.color = c;
        yield return null;
    }
}
1 Answers

According to Microsoft's C# documentation, IEnumerator is just a useful interface for iterating through a collection of objects. It defines a MoveNext() method and a Reset() method for navigating the collection it is attached to. Coroutines can be executed across many frames, so Unity likely uses IEnumerator to iterate across the Coroutine's state changes as each frame progresses.

You can find the declaration of the Coroutine methods in the MonoBehavior bindings within Unity's source code here.

Related