- Home /
How to retrieve current shown hierarchy?
Lets say I dont know ANY of the names of ANY of the current objects in the scene right now. Ofcause I know at least one, the one where this script will be attached.
But, there are multiple hierachies active at the same time and I want the user to be able to post a debug back to our server later.
They are all initiated from different scripts, so there is no global list of my own.
How can I trace/debug.log all objects? what collection or how do I list the objects in Hierarchy right now.
I want to make a "List all" button that goes through them all and print their names with Debug.Log().
Of cause if everything is inside a single "root" then I could just find childrens, but there isnt or is there a secret/hidden root object in unity3D ?
This is what I've got so far:
void DebugRoot()
{
Debug.Log("----- Debug root -----");
Transform trans = transform.root;
DebugDeeper(trans);
}
void DebugDeeper(Transform trans)
{
int children = trans.GetChildCount();
Debug.Log(trans.name + " has " + children);
for (int child=0;child<children;child++)
{
DebugDeeper( trans.GetChild(child) );
}
}
It prints the hierachy below the object where I attach the script, but there are more root elements within the hierachy, so I need to ajust transform.root somehow or find a list of root(s) ???
Answer by BerggreenDK · Jul 19, 2011 at 11:19 PM
aha! Got it! posting this as the answer for everyone else. Please let me know if you can use it too. Then I might post more such scripts in the future.
void DebugRoot()
{
Debug.Log("----- Debug root -----");
foreach (GameObject go in Object.FindObjectsOfType(typeof(GameObject)))
{
if (go.transform.parent == null)
{
DebugDeeper(go.transform);
}
}
}
void DebugDeeper(Transform trans)
{
int children = trans.GetChildCount();
Debug.Log(trans.name + " has " + children);
for (int child=0;child<children;child++)
{
DebugDeeper( trans.GetChild(child) );
}
}
Answer by idbrii · Aug 14, 2020 at 12:05 AM
Similar answer but instead of Object.FindObjectsOfType(typeof(GameObject)), use SceneManager.GetActiveScene().GetRootGameObjects() so you only look at each object once. (FindObjectsOfType should find every object. GetRootGameObjects only gives the top-level ones so we can print them with their children.)
[UnityEditor.MenuItem("GameObject/PrintHierarchy")]
static void PrintHierarchy()
{
Debug.Log("Print object hierarchy");
foreach (var obj in SceneManager.GetActiveScene().GetRootGameObjects())
{
Debug.Log("Root object");
PrintChildren(obj.transform, "");
}
}
static void PrintChildren(Transform t, string indent)
{
int child_count = t.childCount;
Debug.Log($"{indent}'{t.name}' has {child_count} children");
var more_indent = indent + "\t";
for (int i = 0; i < child_count; ++i)
{
var child = t.GetChild(i);
PrintChildren(child, more_indent);
}
}