- Home /
Help? Im trying to get my zombie prefab to spawn, but stop them spawning after a set spawn limit.
Here is my code, i cant seem to figure out whats wrong. Thanks in advance!
#pragma strict
var zombiePrefab : GameObject; // Prefab to spawn
var zombiesSpawned : int; //Zombies Spawned
var Player : GameObject; //player
var spawn : boolean;
var minWait : int;
var maxWait : int;
var waitTime : int;
var spawnLimit : int;
function Start () {
minWait = 1;
maxWait = 10;
waitTime = Random.Range(minWait, maxWait);
spawn = true;
}
function Update () {
if(spawn)
{
Spawn();
}
if(zombiesSpawned < spawnLimit)
{
spawn ();
}
else
{
spawn = false;
}
}
function Spawn() {
Instantiate(zombiePrefab, transform.position, transform.rotation);
zombiesSpawned +=1;
NewWaitTime();
spawn = false;
SetSpawn();
}
function SetSpawn() {
yield WaitForSeconds (waitTime);
spawn = true;
}
function NewWaitTime() {
waitTime = Random.Range(minWait, maxWait);
}
Answer by Kiwasi · Jul 14, 2014 at 07:08 PM
You've got some weird stuff going on here.
First delete lines 21 to 24. These lines will attempt to spawn a zombie every time spawn is true, regardless of the number of zombies that are present.
2nd up you really need two bools to manage this. You should use one to manage the timer and another to manage the spawn limit.
An even better way would be to manage the whole thing through a single coroutine. The advantage of this is there is no need to check any variables each frame. In fact once you have finished spawning there is no overhead. Here is some pseudo code you can use. Might be a couple of errors as I don't usually do JavaScript.
#pragma strict
var zombiePrefab : GameObject; // Prefab to spawn
var minWait : int = 1;
var maxWait : int = 10;
var spawnLimit : int;
function Start () {
spawn ();
}
function Spawn() {
var zombiesSpawned : int; //Zombies Spawned
while (zombiesSpawned < spawnLimit){
Instantiate(zombiePrefab, transform.position, transform.rotation);
zombiesSpawned +=1;
yield WaitForSeconds (Random.Range(minWait, maxWait));
}
}
Thank you for the reply but I'm still having some issues. Its telling me, "Its not possible to invoke the expression type boolean." Any help you can give me?