Limiting respawns on scene

Hi there

I just wanted to know what is the cheapest way of instantiating prefabs at spawn points, whilst keeping control of how many objects are in the scene. At the moment i have this, but i think it might be too computationally expensive. :s Basically i want to spawn enemy soldiers at random points of the map, but i want to control limit it to soldierMax.

#pragma strict

var prefab:GameObject; 
var soldierMax:int;
private var soldierCount:int; 
private var respawnPoints:GameObject[];
private var maxSpawnDelay:int;

function Start () {
 	respawnPoints = GameObject.FindGameObjectsWithTag("SoldierSpawn");	

function Update () {
	if(soldierCount < soldierMax) {
	else {
		soldierCount = GameObject.FindGameObjectsWithTag("Soldier").length;

function respawnSoldier() {
	while (soldierCount < soldierMax) {
		yield WaitForSeconds(Random.Range(0,maxSpawnDelay));

Would appreciate the guidance :slight_smile:

Thanks guys

Looks pretty good just as is, only part im not seeing reason behind is the else statement.I assume you are handling the destruction of the prefab else were in the script or you just don’t want any more than max count to spawn. if you want a constant number up then you need to add a line decreasing you soldier count by one so your update picks up your one short.