How do you queue a list of actions?

I was reading the Unity scripting guide on this and they suggested using yields and coroutines. However, they mentioned that it doesn’t work in an Update or FixedUpdate function and that’s exactly where I think I need to use it (I am a beginner, I could be totally wrong).

I’m trying to get a block to randomly choose a direction and go in that direction for a given amount of time. However, for some reason it won’t execute the entire turning function (e.g. when I tell it to turn 90 degrees it seems to only turn 3 before randomly choosing another direction). My code thus far looks like this:

var direction:int;
var degrees:float;

function Update ()
{	
	direction = Mathf.Floor(Random.value * 4);

	switch(direction)
	{
		// move forward
		case 0:
			StartCoroutine(moveForward());
			break;
		// make a 180 and move forward
		case 1:
			StartCoroutine(turn(-180));
			StartCoroutine(moveForward());
			break;
		// turn right and move forward
		case 2:
			StartCoroutine(turn(90));
			StartCoroutine(moveForward());
			break;
		// turn left and move forward
		case 3:
			StartCoroutine(turn(-90));
			StartCoroutine(moveForward());
			break;
	}
}

function moveForward ()
{
	transform.Translate(0, 0, 2 * Time.deltaTime);
	yield WaitForSeconds(5);
}

function turn (degrees)
{
	transform.Rotate(0, degrees * Time.deltaTime, 0);
	yield WaitForSeconds(5);
}

Any help would be much appreciated, thank you!

That won’t work because you’re starting new instances of a coroutine every frame. It would be better to not use Update at all, since it runs every frame and can’t be interrupted or delayed. Just to illustrate:

function Start () {
    while (true) {
	    var direction = Random.Range(0, 4);
	    Debug.Log (direction);
	    yield WaitForSeconds(1);
    }
}

Also, you can use Random.Range instead of Random.value like that, and variables that don’t need to be global should always be declared inside functions. (Also it would be better to follow the convention of using uppercase for classes and functions, and lowercase for variables. Plus you should always declare the type for all variables, either explicitly, or implicitly by supplying a value, so “function turn (degrees)” is incorrect; instead it would be “function turn (degrees : float)”, and as I mentioned “degrees” should not be a global variable.)

Also, if your intentions are to have the object rotate first, then move, you should yield on the first coroutine instead of having both execute simultaneously. I’d recommend using Lerp as well, instead of Translate and Rotate, since those will result in cumulative accuracy errors over time, especially with low framerates (see MoveObject).