- Home /
FindGameobjectsWithTag -> Array
GameObject[] Swordmen = new GameObject[10];
void Start () {
Swordmen = GameObject.FindGameObjectsWithTag ("Swordman");
}
It won't add the game objects to the array and if I try this:
GameObject swordman;
swordman = GameObject.Find("Swordman2");
Swordmen [1] = swordman;
It will just say: IndexOutOfRangeException: Array index is out of range.
Please help, it's probably really obvious but I just don't see it. (And I'm making a enemy array where I can get one and activate it when I need it, I tried to instantiate them into the array but it didn't work either, after it was instantiated if I tried to refer to it I got an error)
Are the GameObjects actually **tagged** with the tag "Swordman" (case sensitive) or are they only named "Swordman"?
Answer by Uncasid · Jan 20, 2014 at 02:51 PM
remember that c# uses 0 based arrays, ie Swordmen[0] is actually the first swordman.
how many swordmen do you have in the scene? also, make sure they are enabled in the scene.
btw
GameObject[] Swordmen = new GameObject[10];
should just be: GameObject[] Swordmen;
this is because you wont actually know the size of the array coming from the findobjectswithtag method.
The gameobjects weren't enabled and yes I did try leaving new GameObject[]; out but didn't help obviously.
Answer by Ibzy · Jan 20, 2014 at 02:57 PM
I've always struggled with arrays like this in Unity too, instead I'd use List Swordmen = new List;
void Start() {
Swordmen.AddRange(GameObject.FindGameObjectsWithTag("Swordman");
}
This is pseudo code, so don't quote me, but I believe something along those lines may work. If FindGameObjectsWithTag() returns an array itself, this might require a for loop?
Edit: Code amended - thanks go out to Uncasid.
Lists are nice to use for sure, LINQ is one bad mother and quite useful. Just to note, you have the incorrect method call to add an array to a list object:
Swordmen.Add(GameObject.FindGameObjectsWithTag("Swordman");
should be
Swordmen.AddRange(GameObject.FindGameObjectsWithTag("Swordman");