Coroutines in Unity3d (Javascript version)

I’ve been working with Unity3d for some time now and I couldn’t really make good use of the coroutines because I was unable to truly understand them. After some time playing with them and making some experiments I realized their true power. I couldn’t believe what I was missing! So, a couple of fellow game devs asked me to explain the concept to them. I decided that a blog post was the perfect way to do it and, at the same time, share this with everyone.

Coroutines: Special type of functions(in the programming sense) that allows to stop it’s own execution until certain condition is met.

When you invoke this function (start the coroutine) it will behave just like any other normal function you have ever seen, until it reaches the yield instruction. The yield instruction explained: The yield instruction works like a return statement in the sense that it stops the execution of the function and returns control to the code that invoked that function. The main difference is that the yield instruction lets you delay the execution of the code that is after it (in the last example, the DoSomethingElse() statement).

Great explanation! Along with the Unity Documentation now I finally get this. Thanks a lot!

2DAray

As far as I can tell, these would work the same UNLESS the functions you’re calling are also coroutines – if myFunctionA has a yield that waits for the next frame, then the first version of the original function won’t call myFunctionB until myFunctionA has finished.