loop

Heya. I just want to figure out how to make a script loop. Heres code thats wrong because you cant have yield and start together:

var newObject: GameObject;
function Start(){
yield WaitForSeconds(20);
Instantiate(newObject, transform.position, transform.rotation); 
//Loop so this repeats every 20 secs?
}

or

fuction Start(){
audio.Play();
yield(20);
//loop every 20 secs?
}

see what I mean?Start and yield arent friends, so help would be cool. thanks
AC

Actually, Start and yield are very good friends and a great team too.

Sorry, my confusion. I meant Update and yield. So how do I make a script like these loop indefinately? :roll:
Cheers

Use a “while loop” for this.

var newObject: GameObject;

function Start() { 
	while (true) {
		yield WaitForSeconds(20); 
		Instantiate(newObject, transform.position, transform.rotation); 
		//Loop so this repeats every 20 secs? 
	}
}

A while loop will keep executing the code inside of it as long as the expression inside the parentheses evaluates to true. Above it is “(true)” which will always be true.

You don’t ever want to put yield statements in Update() since it is called every frame. You can however start coroutines and call other functions from inside Update(), but that’s not what you want to do in this case.

Also, code formatting like I have done above really helps. I recommend it.

Cheers,
-Jon

Fantastic. Thanks Jon.
AC