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.

A coroutine looks like this (on javascript, the C# version is here):

function MyCoroutine()
{
	DoSomething():
	yield;                         //Mystery here
	DoSomethingElse();
}

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).

function MyCoroutine()
{
	DoSomething():			//Do this immediately
	yield;                          //Return control to the caller
	DoSomethingElse();		//This will be executed one frame later
}

void Start()
{
	MyCoroutine();
}

What happens if you have more code after the MyCoroutine call? Let’s see an example with some prints:

function MyCoroutine()
{
	print("This is printed second");
	yield;    	//Return control to the Start function
	print("This is printed one fourth, exactly one frame after the third");
}

void Start()
{
	print("This is printed first");
	MyCoroutine();
	print("This is printed third");
}

You can control when do the code after the yield instruction will be executed. It depends on the parameter of the yield instruction, according to the following table

Nothing: It will wait one frame
Another coroutine invocation: It will wait until the invoked coroutine finishes execution
A WaitForSeconds object: It will wait certain amount of time

Confused? Here are the examples:

function MyCoroutine()
{
	DoSomething():				//Do this immediately
	yield WaitForSeconds(2);   	//Return control to the caller
	DoSomethingElse();			//This will be executed 2 seconds after
}

void Start()
{
	MyCoroutine();
}
function MyCoroutine()
{
	DoSomething():				//Do this immediately
	yield MyOtherCoroutine();   //Go and execute MyOtherCoroutine!
	DoSomethingElse();			//This will be executed after MyOtherCoroutine finished execution
}

function MyOtherCoroutine()
{
	DoStuff():				//Do this immediately
	yield WaitForSeconds(2);   	//Return control to the caller (in this case the Start function)
	DoMoreStuff();			//This will be executed 2 seconds after
	//MyOtherCoroutine finishes execution here
}

void Start()
{
	MyCoroutine();
}

As you can see, coroutines are very powerful and easy to use once you understand how they work. I will post some usage examples and the C# version of the scripts on this post soon.

  • Pingback: Coroutines in Unity3d (C# version) - Silent Kraken

  • am

    hi!
    Thank you for the post. Useful in did. I’m not sure about one thing, what’s the difference between writing this:
    yield myFuntionA();
    yield myFuntionB();
    yield myFuntionC();

    or this:
    myFuntionA();
    myFuntionB();
    myFuntionC();

    Does yield asures that each function is executed till the end before calls the next one? I’m confused…

    [WORDPRESS HASHCASH] The poster sent us ’0 which is not a hashcash value.

  • http://twitter.com/Protodeep Barrett Fox

    Thanks for this. Just-in-time info. My favorite kind.

  • rohini

    very nice center

  • Dhez20

    Great Unity resource
     http://www.frogames.net/?r=38

  • http://twitter.com/fran_sevillano frowing

    Clearest explanation I’ve seen, congratulations!

  • Pingback: Unity3D Yielding | Pirate's Hold

  • Kris Kirov

    You made my day Mr. Rodriguez.God bless You!

  • http://www.facebook.com/pg.preeth Preeth PG

    awesum… phew. finally i got a good tutorial

  • Eduardo

    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.