I'm trying to mimic FindGameObjectsWithTag
with FindGameObjectswithName
. I know using tags is faster, but I'm trying create a way to search for objects I spawn with a child object I name on instantiation through the inspector.
My goal is create multiple enemy spawners. My current spawner has a drag and drop variable for enemyprefabs. It looks for enemies tagged "ReSpawn", then checks if that length is below (x) to start spawning more. I would like to upgrade my current single spawner to still check for enemies named respawn, but then check if those respawn have a child object named "blank" (an input string name I can specify in the editor).
This way, I can set the enemy spawners anywhere (near water, tall grass, forests, etc), and when I defeat one, the specific spawner will instantiate one of its opponent for that area.
Here is my code
var ThisSpot:String;
var Oppos : GameObject[];
var OppoCount : GameObject[];
var HowMany = 3;
var spawnSizeArea = 25;
function Start() {
StartCoroutine ("Spawn");
}
function Update () {
OppoCount = GameObject.FindGameObjectsWithTag("Respawn");
// OppoCount = GameObject.FindWithName(ThisSpot); This is what I am trying to achieve
if(OppoCount.length < HowMany) {
StartCoroutine ("Spawn");
}
}
function Spawn() {
var length = Oppos.length-1;
var index = Mathf.Round(length*UnityEngine.Random.value);
curSpawn = Oppos[index];
var xz = Random.insideUnitCircle * spawnSizeArea;
var newPosition = Vector3(xz.x,0,xz.x)+transform.position;
yield WaitForSeconds(Random.Range(70,120));
Instantiate(curSpawn, newPosition, transform.rotation);
// Then I could use these 2 lines of code below to use multiple spawners
//var newOp : GameObject = Instantiate(curSpawn, newPosition, transform.rotation);
//newOp.transform.Find("fighter").gameObject.name=ThisSpot;
StopCoroutine("Spawn");
}
EDIT: the solution. Instead of looking for gameobject names/tags, just keep track of a list
**function Update () {
for (var i =0; i < OppoCount.length ; i ++)
if(OppoCount.length > 0){
if (OppoCount[i].gameObject == null)
OppoCount.RemoveAt(i);
}
if(OppoCount.length < HowMany){
StartCoroutine ("Spawn");
}
}
function Spawn(){
var length = Oppos.length-1;
var index = Mathf.Round(length*UnityEngine.Random.value);
curSpawn = Oppos[index];
//var newPosition = Random.insideUnitCircle* spawnSizeArea;
var xz = Random.insideUnitCircle * spawnSizeArea;
var newPosition = Vector3(xz.x,0,xz.x)+transform.position;
//yield WaitForSeconds(Random.Range(70,120));
yield WaitForSeconds(Random.Range(2,4));
//Instantiate(curSpawn, newPosition, transform.rotation);
var newOp : GameObject = Instantiate(curSpawn, newPosition, transform.rotation);
//newOp.transform.Find("fighter").gameObject.active = false;
OppoCount.Push(newOp);
StopCoroutine("Spawn");
}**