- Home /
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) {
respawnSoldier();
}
else {
soldierCount = GameObject.FindGameObjectsWithTag("Soldier").length;
}
}
function respawnSoldier() {
while (soldierCount < soldierMax) {
Instantiate(prefab,respawnPoints[Random.Range(0,respawnPoints.Length)].transform.position,Quaternion.identity);
yield WaitForSeconds(Random.Range(0,maxSpawnDelay));
}
}
Would appreciate the guidance :)
Thanks guys
Just have some central counter object, that increments an integer every time you spwan something! That way you dont' need to keep making calls to 'GindGameObjectsWithTag', which is as you say quite expensive. Decrement the same counter every time something gets destroyed using the OnDestroy function to guarantee success.
Im getting a strange error randomly when they spawn, what is "transform.position assign attempt for 'spawnSoldier(Clone)' is not valid. Input position is {NaN, 0.262370.NaN}" i have no idea how to fix this :S
Answer by bodec · Apr 18, 2012 at 03:56 AM
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.
yup removed the else. Im getting a strange error randomly when they spawn, what is "transform.position assign attempt for 'spawnSoldier(Clone)' is not valid. Input position is {NaN, 0.262370.NaN}" i have no idea how to fix this :S
not sure hopefully some people with more experance in scriptting log on soon and may know the answer
Your answer
Follow this Question
Related Questions
Creating a single-line function for GameObject.Find and GetComponent (for multiple components) 3 Answers
Get components of multiple instantiated objects? 2 Answers
GetComponent vs AddComponent 3 Answers
Instantiated Prefab using its transform and object on other scripts 1 Answer
Getcomponent error? 1 Answer