- Home /
Spawning trouble
Hello, I'm having trouble with a script for Mass Spawning to create a swarm of enemies in a side scrolling shooter game. It respawns but makes more than the intended number. Also they are too closely summoned, so I wanted to add a Wait function before continuing the loop but the code didn't seem to work. Does anyone have suggestions?
//What enemy are we spawning? var Enemy: GameObject; //Add regular timer here and rest timer function Update () { //Is the enemy already Out? //Change to timer in future? if (GameObject.FindWithTag("Enemy") == false){ Wait 0 seconds before triggering the Mass Spawn function Invoke("MassSpawn", 0); } else { CancelInvoke(); } }
function MassSpawn(){ //Set up a loop to add until i =5, loop 5 times, make 5 respawns for(var i: int = 0; i < 5; i++ ){ //WaitForSeconds(1); Instantiate(Enemy, transform.position, Quaternion.identity);
}
}
Answer by Mike 3 · Jul 31, 2010 at 02:18 PM
You want to call the function normally instead of using Invoke if you want to use it as a coroutine, and then use yield before WaitForSeconds. You also need some sort of check to make sure you're not running the coroutine multiple times. e.g.:
//What enemy are we spawning? var Enemy: GameObject; var spawning = false;
//Add regular timer here and rest timer function Update () { //Is the enemy already Out? //Change to timer in future? if (!spawning && GameObject.FindWithTag("Enemy") == null){ MassSpawn(); } }
function MassSpawn() { if (spawning) yield break; spawning = true; //Set up a loop to add until i =5, loop 5 times, make 5 respawns for(var i: int = 0; i < 5; i++ ){ yield WaitForSeconds(1); //this should work now Instantiate(Enemy, transform.position, Quaternion.identity); } spawning = false; }
if (spawning) yield break; Causes an error to appear but remove that and it works. Thanks.
Oh, sorry, bit of c#there. It was more of a precaution anyway, as it was already checked outside the function.
Your answer

Follow this Question
Related Questions
How to use a script on multiple gameobjects, then change a variable for one of them, not the other. 3 Answers
Multiple Spawn Points 1 Answer
Tornado Twins Tutorials. How to add A Respawn and Game Over. HELP! 2 Answers
Respawning and getting hit script Help? 1 Answer
instantiated objects animation making the object reset to 0,0,0?? 1 Answer