Search Unity

C# Get All GameObjects Parented to Parent, Grandparent, Great Grandparent

Discussion in 'Scripting' started by kenaochreous, Aug 1, 2015.

  1. kenaochreous

    kenaochreous

    Joined:
    Sep 7, 2012
    Posts:
    395
    I want to get all of the gameobjects attached to the parent regardless of their position in the parent's hierarchy. Some of the gameobjects attached to the parent are great grandchildren to the original parent. Is there easier way of finding all of the gameobjects attached to the parent other than a series of for loops?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    wait, your thread says "get all gameobjects parented to parent, grandparent, great grandparent", but in your question you bring up grandchildren.

    Which is it?

    Are you saying you want to find the top most parent from the current gameobject, and then get all the children of that?

    Well, Transform.root is the top most grandparent:
    http://docs.unity3d.com/ScriptReference/Transform-root.html

    As for getting all the children, you have to do that as a loop.

    Of course if you use 'GetComponentsInChildren' and request for 'Transform', it'll loop over all children for you and return the Transforms for them all:
    http://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html

    I'm not sure how efficient this would be relative to looping over all children. It may or may not be faster. GetComponentsInChildren is implemented internally in the c++ side of unity, no idea what optimizations they have on that. If they don't, that's a GetComponent call on every child... could be slow.

    Personally this is how I get all children:
    Code (csharp):
    1.  
    2.         public static IEnumerable<Transform> GetAllChildren(this Transform t)
    3.         {
    4.             //we do the first children first
    5.             foreach (Transform trans in t.transform)
    6.             {
    7.                 yield return trans;
    8.             }
    9.  
    10.             //then grandchildren
    11.             foreach (Transform trans in t.transform)
    12.             {
    13.                 foreach (var child in GetAllChildren(trans))
    14.                 {
    15.                     yield return child;
    16.                 }
    17.             }
    18.         }
    19.  
    Found at line 816 here:
    https://github.com/lordofduct/space...ob/master/SpacepuppyBase/Utils/GameObjUtil.cs
     
    Last edited: Aug 1, 2015