Would it be true to say “A coroutine is just a function with yield somewhere in it?”
At least in javascript, I realise that in C# you have to use IEnumerator. But am I missing anything else? I’m trying to understand the buggers.
Thanks alot
Romano
Not only but somehow yes.
void Start(){
Method();
}
in the case above, when the program hits Method, it stops and jumps to the memory location where Method is stored, then it runs all the code and once it hits the return of the method it gets back where it left off (even when you do not write return, the compiler puts one).
void Start(){
StartCoroutine(Coroutine());
}
in this situation, same thing happens but then the coroutine is placed on a list of coroutine to be run after the update. What you get is that Start starts (…) then the coroutine starts and hits the yield (you need at least one in the method) then returns to the Start which closes. Next frame after the Update is run, the compiler checks for any pending coroutine and finds that one, then it gets back to the yield it quit from previous frame and continues the coroutine until finding another return (whether yield or basic return).
So in a way, a coroutine is a method but that you can pause.
Coroutine are not thread, more likely a process since if you kill the parent object that triggered the coroutine, the coroutine dies with it.
IMHO the main distinction that trips people up is that that coroutines live for a few frames, and how you have to think about that.
A regular function acts and feels like it’s part of you. You call it, it runs and completely finishes, and you continue from the next line. They act as if they were cut&pasted into that part of your code.
A coroutine acts like a different person. You run a function; but it feels like you “spawn off” a coroutine. StartCoroutine is more like Instantiating an empty gameObject with a new script on it. It’s out there, it will start when it feels like it, do it’s own thing, and quit when it feels like it. It won’t especially check in with you or tell you when it’s done. Sort of a “fire&forget.”