why doesn't my custom function work ?

var limit : int = 100;
var enemy : GameObject;
var spawn = true;
var enemiesLeft : int = 100;
function Update(){
Instantiate(enemy , transform.position , transform.rotation);

if(limit == 0){
spawn = false;
if(enemiesLeft == 0){

function wait(){
yield WaitForSeconds(4 * Time.deltaTime);

function OnCollisionEnter(){

What I expected this script to do is
Instantiate an enemy
wait for 4 seconds
Move the enemy prefab forward

Instead what it does is
Instantiate all 100 enemies at the same time
The script doesn’t wait
They all randomly fly across the screen

How can I fix this . I’m kinda guessing it’s to do with the Update function and being spawned from the same point , but I’m not sure how I fix it … Can someone help please ?

Before you wait, set spawn=false;. At the end of wait, just after the yield, set spawn=true;

Coroutines are tricky. What happens is, a new wait() is spawned. It is not the same thing as having WaitForSeconds in Update (only because wait is a coroutine.) It’s like hiring a guy to wait 4 seconds, while you keep running as normal. Of course, the guy has to tell you when it’s been 4 seconds. Using spawn is a way to do that. It’s like Update will just stare at the clock until spawn is set true.

Some people would the entire loop in a coroutine: loop; spawn; waitForSeconds; end loop.

Think you’d also need to move some things around to quit when limit=0.

After yield wait for seconds there is a } it has to be a {
and before if enimiesleft == 0 you have a } delete that one
And after transform.Translate you have one delete that