x


How To Get List of Child Game Objects

Sometimes a game object has child game objects. Likewise, a game object can have a parent. In the past I tried getting all child game objects by using this:

List gs = new List();
 Transform[] ts = gameObject.GetComponentsInChildren<Transform>();
 if (ts == null)
 return gs;
 foreach (Transform t in ts) {
 if (t != null && t.gameobject != null)
 gs.Add(t.gameobject);
 }
 return gs;

But I have recently proven this is unreliable when running from the editor. I have loaded in from a collada file the main game object. In the hierarchy view, I see the game object with all of its children. However, my script returns an empty list.

Can somebody please tell me a reliable way to get child objects?

Can somebody please tell me a reliable way to get the parent game object?

more ▼

asked Jan 13, 2012 at 08:22 PM

msknapp gravatar image

msknapp
346 23 20 21

Basically what I did was AssetDatabase.LoadMainAssetAtPath, and followed it up with GameObject.Instantiate. With the instance it creates, I see in the hierarchy view there are children game objects. Still, the script returns an empty list.

Jan 13, 2012 at 09:00 PM msknapp
(comments are locked)
10|3000 characters needed characters left

8 answers: sort voted first

The suggestions I've seen from smart people like Eric5h5 is to use the build-in transform functions, rather than GameObject.Find. Since it looks like you're using C#, the following is also in C#:

To get children:

foreach (Transform child in transform)
{
  //child is your child transform
}

To get parent:

transform.parent;
more ▼

answered Jan 13, 2012 at 10:36 PM

Julien.Lynge gravatar image

Julien.Lynge
10.2k 87 85 124

why on earth cannot unity just build this capability into their API? ridicolous.

Jan 13, 2012 at 10:41 PM msknapp

Thanks, it's very simple.

Apr 27 at 09:06 PM Srbhunter

Thanks,

Sep 15 at 12:06 PM gulfam131
(comments are locked)
10|3000 characters needed characters left

foreach (Transform child in transform) { //child is your child transform } This is right.

GetComponentsInChildren will get gameObject's transform as well.

more ▼

answered Oct 26, 2012 at 04:02 AM

jason891107 gravatar image

jason891107
1 1 1

(comments are locked)
10|3000 characters needed characters left

foreach(Transform child in transform) is unreliable, as is GetComponentsInChildren, as they won't traverse the entire tree of children.

This will correctly return all the children:

    void Start () {

        Debug.Log("Child Objects: " + CountChildren(transform));
    }

    int CountChildren(Transform a)
    {
        int childCount = 0;
        foreach (Transform b in a)
        {
            Debug.Log("Child: "+b);
            childCount ++;
            childCount += CountChildren(b);
        }
        return childCount;
    }
more ▼

answered Jan 19, 2013 at 07:00 PM

Pix10 gravatar image

Pix10
31 4 5 5

No it won't, you're script returns the number of children not a list of them. Besides you can just use transform.childCount to get the number of children anyway.

Jan 29, 2013 at 09:16 PM ErvinDjinn

As far as I know, "children" refers to the transforms on the next level only, while "descendants" would refer to every transform below this one in the tree. If the goal was to iterate over all descendants, the code example shows a way to do that recursively.

Feb 28, 2013 at 06:49 PM ebogguess
(comments are locked)
10|3000 characters needed characters left

The best Answer would be a recursive function I guess ...

So the function will go and look at the first Transform it finds in transform then it will do whatever you want to do (add it to a list or array or whatever) in this case it will change the active and passive colour stored in a level element... after it has done what it should it will see if the object has any children.

"!" Although this works sometimes there seems to be a real problem with the childCount function in about 50 percent of all objects it does not see the last layer of the hierarchy.

"!!" There is also one problem with this: If you add new layers OnStart of the Game and you also execute the script at the same time as these will get created it might not see them... -?- Is there any way to time this or should I just use a yield WaitForSeconds in the start function...?


public void Start () 
    {
        StartCoroutine(OverrideAllChildren(transform));
    }

    public IEnumerator OverrideAllChildren(Transform pTransform)
    {
        foreach(Transform child in pTransform)
        {
            TouchQube temp = child.GetComponent<TouchQube>();
            if(temp != null)//If it is a TouchQube
            {
                totalCount++;
                if(overrideInactive){temp.SetInactiveLight(overrideColor);}
                if(overrideActive){temp.SetActiveLight(overrideColor2);}
            }
            Debug.Log(child.name+" has "+CountChildren(child)+" children. TotalOverwritten: "+totalCount);
            if(HasChildren(child))//If it has children
            {
                StartCoroutine(OverrideAllChildren(child));
            }
        }
        yield return(true);
    }

    public bool HasChildren(Transform pTransform)
    {
        int count = 0;
        foreach(Transform child in pTransform)
        {
            count++;
        }
        if(count > 0){return true;}else{return false;}
    }

    public int CountChildren(Transform pTransform)
    {
        int count = 0;
        foreach(Transform child in pTransform)
        {
            count++;
        }
        return count;
    }

more ▼

answered Jan 13 at 10:50 PM

Dinkelborg gravatar image

Dinkelborg
15 2 3 4

(comments are locked)
10|3000 characters needed characters left
        public List<GameObject> Children;


        foreach (Transform child in transform)
        {
            if (child.tag == "Tag")
            {
                Children.Add(child.gameObject);
            }
        }

In c# you can use this code to get all the child objects with a certain tag.

more ▼

answered Jun 07 at 02:40 PM

pprofitt gravatar image

pprofitt
1

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x660
x648
x292
x30

asked: Jan 13, 2012 at 08:22 PM

Seen: 59368 times

Last Updated: Sep 15 at 12:06 PM