- Home /
store GameObject.FindGameObjectsWithTag in an array
I have a level with 10 objects in it, each one with a tag from 0-9. I want these objects to enable themselves one at a time e.g. kill one enemy, the next one becomes active etc. Can i set all of my ships into an array using GameObject.FindObjectsWithTag?
bool status;
void Start()
{
GameObject ships = GameObject.FindGameObjectWithTag ("ship" + number);
foreach (GameObject ship in ships)
{
status = false;
}
}
So I would like to find all the ships in the beginning of the level and set all of their status' to false. Is this possible?
Answer by LessThanEpic · Aug 22, 2014 at 09:30 PM
FindGameObjectsWithTag returns an array of GameObjects, but if the objects you want to find have different tags (ship0, ship1, etc.) then FindGameObjectsWithTag will only find one game object at a time and your array will only have one item in it.
One approach would be to build your array manually. Something like the following:
private int shipCount;
void Start()
{
GameObject[] ships = new GameObject[shipCount];
for(int i = 0; i < shipCount; i++)
{
ships[i] = GameObject.FindWithTag("ship" + i);
ships[i].SetActive(false);
}
}
Answer by Cherno · Aug 22, 2014 at 09:18 PM
Delcare the ships variable as array. GameObjects can be enabled with .enabled = true/false.
GameObject[] ships = GameObject.FindGameObjectWithTag ("ship" + number);
foreach (GameObject ship in ships)
{
ship.enabled = false;
}
I tried that just before I posted but it has a problem with converting from an array, throws me this error:
I see... From looking at the Scripting API, it only returns one gameObject with the specified tag at most.
Ins$$anonymous$$d of searching by tag, you could either iterate through all gameObjects in the scene:
GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
foreach (GameObject go in gos) {
if(go.compareTag("ship" + number)) {
}
}
Or, what would be faster, search for a script that these ship objects have:
ScriptOnShipObjects[] shipsScripts = FindObjectsOfType(typeof(ScriptOnShipObjects)) as ScriptOnShipObjects[];
foreach (ScriptOnShipObjects shipScript in shipsScripts ) {
shipScript.gameObject.enabled = false;
}