Trying to spawn one object every 15 seconds (Javascript)

Like the title says, I’m trying to make it so that every 15 seconds a new enemy will appear, to a max of 5 (plan to increase this to 80 later). However with this script:

public var enemyPrefab:GameObject;
public var enemyScripts:ArrayList = new ArrayList();

var enemyNumber = 1;
var maxEnemies = 5;

function Update()
{
	spawnEnemy();
}

function spawnEnemy()
{
	while(enemyNumber < (maxEnemies))
	{
		yield WaitForSeconds(15);
		currentEnemy = Instantiate(enemyPrefab, transform.position, transform.rotation);
		enemyNumber++;

	}
}

It waits 15 seconds, then spawns and spawns and spawns infinitely (or until I have to close Unity with the task manager), without waiting between spawns or paying any attention at all to the “maxEnemies”. I proceeded to try the relevant (at least I thought they were relevant) portions of the script here: http://www.cgauiwtalk.com/showthread.php?16136-Script-Spawning-Enemies

(“Relevant portions”)

private var enemyNumber = 1.0;
var enemyNumberMax = 10;
var enemyPrefab : GameObject;

function Update () 
{
	spawnEnemy();
}

function spawnEnemy ()
{
	while (enemyNumber <=(enemyNumberMax))
	{
		currentEnemy = Instantiate(enemyPrefab, transform.position, transform.rotation);
		enemyNumber++;
		yield new WaitForSeconds (15);
	}
}

And it pays attention to the max number (although it seems to go 1 over), however it does not wait at all, it spawns all enemies at startup. Anybody have any ideas what I’m doing wrong here?

edit: Forgot to say, I’ve tried the WaitForSeconds in the update as well, but it either A. Still gets ignored, or B. Completely negates everything in the spawn function.

Update runs every frame without exception and can’t be made to yield; don’t use Update unless you want something to happen literally every single frame. Making your spawn function a coroutine and then launching it from Update means you’re starting another instance of your coroutine every frame. Just use InvokeRepeating:

var enemyPrefab : GameObject;
private var enemyNumber = 1;
var maxEnemies = 5;
var spawnWaitTime = 15;

function Start () {
	InvokeRepeating ("SpawnEnemy", .01, spawnWaitTime);
}

function SpawnEnemy () {
	if (enemyNumber != maxEnemies) {
		enemyNumber++;
		currentEnemy = Instantiate(enemyPrefab, transform.position, transform.rotation);
	}
}

Thanks a lot, that seems to have fixed everything :slight_smile: