- Home /
getting the children of the first level in hierarchy
if i have this hierarchy:
root
object a
subobject a-1
subgroup a-2
subobject a-2-1
subobject a-2-2
subobject a-3
object b
subobject b-1
subobject b-2
object c
subobject c-1
subobject c-2
how to get the first level children with the parent being, for example, object a? if i use Array(objecta.GetComponentsInChildre(Transform)) then i get not only first level which is subobject a-1,subgroup a-2 and subobject a-3 but also children of the subgroup a-2
is there a way to get the first level children of given parent? thanks, any help appreciated!
Answer by Mike 3 · Nov 29, 2010 at 12:35 PM
Something like this:
Array array = new Array();
for (var child : Transform in objecta.transform) { array.Add(child); }
Answer by V-Jankaitis · Oct 11, 2017 at 01:55 PM
public static Transform[] GetTopLevelChildren(Transform Parent)
{
Transform[] Children = new Transform[Parent.childCount];
for (int ID = 0; ID < Parent.childCount; ID++)
{
Children[ID] = Parent.GetChild(ID);
}
return Children;
}
this is vine, I'll be adding this to my utils class.
I was thinking of doing similar way like get all childrens and check if the parent transform was the given one, it it was then it was the first levle child , similar to yours. I asume childcount will only count first level children tho, otherwise won´t work.
Answer by frogsbo · Jun 11, 2014 at 03:29 AM
first level children:
var g = Selection.activeGameObject;
for (var child : Transform in g.transform)
all children:
var g = Selection.activeGameObject;
var allChildren = g.GetComponentsInChildren(Transform);
for (var child : Transform in allChildren) {}
Answer by drudiverse · Jul 20, 2014 at 12:38 PM
The transforms are returned in order of the top level downwards if you get all objects in the parent, so if you know the number of children that should be in the first level. i.e. 16, you can just cycle through objects 1-17 of the array... object 0 with be the parent.
so using that method, it's possible to cound the first level childs using the first option, and then read from all transforms using that number + 1 to skip the parent.
Your answer
Follow this Question
Related Questions
Hierarchy Foldout Variables Wanted 3 Answers
transform.Find always returns null 1 Answer
Change an object's grandparent 2 Answers
Is there a way to make clones appear as children in the hierarchy? 3 Answers
I can't move gameobjects or create parents/children in the hierarchy menu, what's going wrong? 1 Answer