- Home /
Get all items from hierarchy?
In editor how can I get a list of all items in the hierarchy and possibly refer to each one?
For example create a list from all objects in a text file. I know the text part, but not the get hierarchy list.
Thanks
Answer by yoyo · Feb 23, 2011 at 04:32 PM
You can find all game objects like this:
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
Debug.Log(obj.name);
}
If you want to traverse down the hierarchy from a specific object, do something like this:
void Traverse(GameObject obj) { Debug.Log(obj.name); foreach (Transform child in obj.transform) { Traverse(child.gameObject); }
}
To traverse the whole scene from the root, combine the above into something like this:
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.transform.parent == null)
{
Traverse(obj);
}
}
Note that as of Unity 4.6 FindObjectsOfType will not include inactive GameObjects.
In my experimentation I've also found this method misses out some active objects, which is rather odd. I wonder if it might be something to do with the hideflags.
What if obj is object that has child's.So it makes it array.And than i want to foreach that obj.But it would say "foreach statement cannot operate on variables of type UnityEngine.GameObject' because it does not contain a definition for
GetEnumerator' or is not accessible".Because that object is not defined as an array.But if you say "foreach (GameObject[] obj)" than you cant get objects that are not array sadly :( Please help on this one !
@Siliproksi I tested this code mate, it works on all levels. here, does your code look like this?
void Traverse(GameObject obj)
{
Debug.Log (obj.name);
foreach (Transform child in obj.transform) {
Traverse (child.gameObject);
}
}
// Use this for initialization
void Start () {
foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.transform.parent == null)
{
Traverse(obj);
}
}
}
Answer by Siliproksi · Aug 30, 2016 at 01:58 PM
@ProbePlayer Oh sorry i didnt saw that. No my code is not like that.But i am pretty sure it works like that.I didnt saw that Traverse function you mentioned.Anyways i found that i dont even need it xD :) But yea this is great way to do it.Thanks :)
Your answer
Follow this Question
Related Questions
Gibt es eine Lösung/Einstellung für: Hierarchy Custom / My Sort? 1 Answer
Object not selected in hierarchy gives an error 0 Answers
How to show an icon in Hierarchy view 5 Answers
Detect on Editor Mode drop prefab to the hierarchy 1 Answer
Overwrite the inspector window on Scene Asset heading chosen in the hierarchy window 0 Answers