PlaceholderGames / DinoPark-2017

repo for Dino Park 2017, the testbed for CS3S667
2 stars 0 forks source link

Unity Get GameObject with tag ... in children #33

Closed ghost closed 6 years ago

ghost commented 6 years ago

Does anyone know how to go about Only returning gameobjects of a specific tag in the children of another game object.

I currently have 2 gameobjects that hold an array of game objects of type 'DinoStats' but without the restriction of only adding the children of the current gameobject, all objects are being added to the array.

image

image

HUDStatPanels = GameObject.FindGameObjectsWithTag("DinoStats");

I need that Line of code to restrict the selection to only objects in the parent objects children

Nicky-Jones commented 6 years ago

if im not mistaken to access to a specific child object, with you knowing the specific number in the list of child objects then you do something like this

HUDStatPanels = ParentGameObject.GetChild(Here being the number in the list the child is at e.g. 3rd child in the parents list of child objects).gameObject;

i believe you could also do

HUDStatPanels = GameObject.FindGameObjectsWithTag("DinoStats").GetChild(1).gameObject too.

ghost commented 6 years ago

Apparently neither of those suggestions are valid options in this build of unity.

ghost commented 6 years ago

Found the solution

I was trying to avoid this solution however it turns out it was more useful that I thought.

foreach (Transform child in transform) {
            if(child.CompareTag("DinoStats")){
                HUDStatPanels.Add (child.gameObject);
            }
        }

You can retrieve the gameobject component through an objects Transform component via

object.gameObject