- Home /
Get last children of a node?
I have the following hierarchy:
gameObject 1
gameObject A
gameObject i
gameObject k
gameObject B
gameObject ii
gameObject C
And I want to store an array with the last nodes of the hierarchy that are not root, say in this example my array will have this objects
gameObject k
gameObject ii
gameObject C
Any suggestions?
Answer by Bampf · Apr 12, 2012 at 04:06 PM
The standard terminology is to call those nodes "leaves".
Sounds like you need a recursive function that traverses the tree of game objects, adding leaves to the array. Something like the following, but I have not compiled or tested this:
function FindLeaves(var parent : Transform, var leafArray : Array)
{
if (transform.childCount == 0)
{
leafArray.Add(parent);
}
else
{
for (var child : Transform in transform)
{
FindLeaves(child, leafArray);
}
}
}
You would call this function by passing in the root gameObject and an empty array.
Note: when debugging recursive functions if you make a mistake and get an infinite loop you can lock up Unity, unless you are running the scripts in a source level debugger like Mono or Visual Studio. So save your work before pressing Play. :-)
Thanks for this answer (Y) For accessing particular transform/child game object, you can use transform.GetChild() method as well.
Answer by aldonaletto · Apr 12, 2012 at 04:09 PM
You could use a recursive function like the one below to traverse the object hierarchy, identify each last child and add it to the List:
import System.Collections.Generic;
static var lastChildren = new List.< Transform>;
static function GetLastChildren(trf: Transform){
if (trf.parent && trf.childCount == 0){ // if this is a last child...
lastChildren.Add(trf); // add it to the array
} else { // but if not a last child...
// verify all of its children (if any):
for (var child: Transform in trf.transform){
GetLastChildren(child);
}
}
}
To get the last children of some object, pass its transform to this function:
GetLastChidren(someObject.transform);
NOTE: I have little experience with List, thus there may exist some stupid error in the code!
Answer by aljndrrr · Apr 12, 2012 at 04:21 PM
private ArrayList _sons;
void hasChildren(Transform t)
{
int i = 0;
foreach (Transform child in t)
{
hasChildren(child);
i++;
}
if (i == 0)
{
_sons.Add(t);
}
}