Script error??

Hi, umm, I have written this script to re-load the main level after the player has died:

var toLoad : float = 2;

function Start() {
	Screen.lockCursor = true;
}

function Update () {
	if (Input.GetKey ("escape")) {
		Application.Quit();
	}
	yield WaitForSeconds (toLoad);
	Application.LoadLevel (0);
}

However, when I run it, Unity says:

I have no Idea what that means. Could someone help? :?

You’re using yield (which makes a function a corutine) in Update. Update is called every frame, so this would be very very bad.

Try moving

yield WaitForSeconds (toLoad); 
Application.LoadLevel (0);

to your Start function instead

Weird, your right. But what is a coroutine? Never got that error before, probebly because I put yield WaitForSeconds in Collider and Trigger functions, but this works fine, thanks! But still what IS a coroutine? :? :smile:

It means that you cannot use an yield statement in the update loop. The whole code in the update () method is executing every cycle. You cannot pause it, or suspend it’s execution. (That’s the whole point). You can, however suspend the execution of a coroutine for a given amount of time or until the next update cycle. A coroutine, as far as I understand it, is just a function with an yield statement.

You cannot suspend the execution of the update () function but you can start a coroutine from it. Which means that you should just move your code with yield WaitForSeconds in seprate function and call this function instead.
something like this:

function loadLevel (levelToLoad : String, timeToWait : float) {
yield WaitForSeconds ( timeToWait ); 
   Application.LoadLevel ( levelToLoad ); 
}

Eric gave a nice explanation on how coroutines work in this thread:

http://forum.unity3d.com/viewtopic.php?t=38049

edplane - a normal function runs through from start to end, but a corutine breaks off and does it’s own thing.

That’s why it can do things like execute a command, wait a second, then execute another - it’s running along side the other scripts. In C# it’s a bit more formal, but in JS, using a yeild makes your function a corutine.

But Update runs every frame, and you can’t hold it up. As ivkoni mentions, you can make another function and call that from Update though. (I tend to conceptualise it as Update telling someone else to hang around and finish a task)