- Home /
Access one child of object with many duplicate names
Hello,
I'm following a tutorial where we create a cube called "brick" in the hierarchy, then we duplicate it a couple of time, we create an empty object called "row", drag all the "brick" objects under the "row", duplicate the rows a couple of time, create an empty object called wall and put all the rows under it.
So, my Hierarchy looks something like this :
Wall
Row
Brick
BrickRow
Brick
Brick
Now, I make a script and I would like to access my objects from the script. I can use GameObject.Find("Wall") to find my wall and it works fine. I know I could use GameObject.Find("Wall/Row"); but what when I have multiple item called Row? Is there a way to get something like GameObject.Find("Wall/Row[0]")?
I thought I could use the foreach but when I write this line :
foreach( GameObject rangee in mur )
I get the following error : error CS1579: foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for
GetEnumerator' or is not accessible
What am I doing wrong with the foreach? Plus is there a way to use the GameObject.Find on objects that have the same name?
Answer by Bicko · Feb 03, 2012 at 11:16 AM
You need to use Transform instead of GameObject in your foreach, because Transform is IEnumerable and GameObject isn't.
Ok, thank you, it's working well if I use the foreach with an IEnumerable component ins$$anonymous$$d of the GameObject. New question that comes to my $$anonymous$$d and I'm asking it even if I haven't searched for it yet, can you get the GameObject that contains the component we get? (I'll search for this right away)
Still, in the first place, is there a way to get something like GameObject.Find("Wall/Row[0]") since all my bricks share the same name? Can I use the FindObject on objects with the same name?
Accessing the parent of the transform is easy: Transform.parent.
For finding objects with the same name, you're best to use Tags. Have a look at this example and the for loop they set up: GameObject.FindGameObjectsWithTag.