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?
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:
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:
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:
public static IEnumerable<Transform> GetAllChildren(this Transform t)
{
//we do the first children first
foreach (Transform trans in t.transform)
{
yield return trans;
}
//then grandchildren
foreach (Transform trans in t.transform)
{
foreach (var child in GetAllChildren(trans))
{
yield return child;
}
}
}
Found at line 816 here: