In Unity, I call a Coroutine (a method that can yield and returns IEnumerator) via StartCoroutine().
When I forget to use the MonoBehaviour method to start it and try to call the IEnumerator method like a normal method, I don’t get any errors, it just doesn’t seem to work. So I was wondering if there is any reason for that behaviour. Are there cases, where I don’t need StartCoroutine() and can use a normal method call instead?
void Start() {
StartCoroutine(SomeCoroutine());
SomeCoroutine(); //does nothing and doesn't through errors
}
IEnumerator SomeCoroutine() {
//
yield return new WaitForSeconds(1f);
//
yield return null;
}
As far as the compiler knows, a coroutine is in fact a normal method. It’s just a standard function that happens to return IEnumerator; only magic Unity stuff (which the compiler knows nothing about) makes it any different. There’s no way to change that without breaking the compiler so it’s no longer standard C#.
–Eric
1 Like
Unity utilizes a feature part of .Net/Mono to get coroutines.
It’s called an iterator function:
Basically you can create a function that returns a enumerated list that is determined functionally as the enumerator is iterated over.
What unity does with this is that it iterates once per frame over said enumerator. You could think of it like a foreach loop that steps through your function once per frame, where the ‘each’ in the foreach is your yield statements.
So as Eric5h5 points out, it’s just magic by unity, the compiler just looks at it like an iterator funciton which is completely legal in .net/mono.
2 Likes
Thanks! That clears it all up.