- Home /
Spawning enemies if there is no other enemy left.
Hello everyone. In my game, player needs to defend a point. I spawn 6 enemies at their spawn points per 7 seconds with this code :
function Start () {
while(true) {
yield new WaitForSeconds(7);
Instantiate(s1,spawn1.position,Quaternion.identity);
Instantiate(s2,spawn2.position,Quaternion.identity);
Instantiate(s3,spawn3.position,Quaternion.identity);
Instantiate(s4,spawn4.position,Quaternion.identity);
Instantiate(s5,spawn5.position,Quaternion.identity);
Instantiate(s6,spawn6.position,Quaternion.identity);
}
}
But what I actually want is, not to spawn them in every 7 seconds. I want to spawn new enemies when the other spawned enemies are dead. I mean, I don't want more than 6 enemies in the scene at the same time. After all of the 6 enemies are dead, I want to spawn 6 more. After they are dead, 6 more and continue like this. I thought some thing like that: when all "enemy" tagged object are null, instantiate the others. But I could not find a way to do it, any ideas ? Thanks :)
You could use a counter that goes up when an enemy is spawned and down when an enemy is killed, then just check that counter and make sure it's at zero before allowing the spawn to happen again.
but I can't fit any code into the while(true) , when I tried to put if statement into while(true) statement, Unity has crashed. Also I don't know best way to call instantiated enemies.
Yeah I would probably just not do it with the yield statement at all, just run a function to spawn the enemies, then when your counter hits zero run that function again so that this doesn't keep trying to run every seven seconds.
Ok I understand the logic but how am I going to detect spawned enemies. I mean I can use Gameobjectswithtag and make an enemies array by code, but how am I going to know if all the objects in enemies array are null ?
almost answered your own question:
function Update(){
var enemies = GameObject.FindGameObjectsWithTag("enemy");
if(enemies == null)
Regenerate();
}
but my other answer may be quicker...
Answer by Seth-Bergman · Jul 27, 2012 at 10:21 PM
static var enemyCount : int;
function Regenerate() {
if(enemyCount <= 0){
enemyCount = 6;
Instantiate(s1,spawn1.position,Quaternion.identity);
Instantiate(s2,spawn2.position,Quaternion.identity);
Instantiate(s3,spawn3.position,Quaternion.identity);
Instantiate(s4,spawn4.position,Quaternion.identity);
Instantiate(s5,spawn5.position,Quaternion.identity);
Instantiate(s6,spawn6.position,Quaternion.identity);
}
}
function Update(){
if(enemyCount <= 0)
Regenerate();
}
then on the enemies script:
var : dead = false;
function Die(){
if(!dead){
dead = true;
RegenScript.enemyCount--;
}
}
and just call Die() when he dies
thanks, really good way to do what I wanted. I just could not figure it out, now it works :)
Your answer
