- Home /
Is it possible to get all root transforms of the scene hierarchy?
Hey Unity folks! As the title implies I would like to find all root transforms in the scene hierarchy, via a C# script.
Here's the catch: There are a lot of children for each transform.
So far the methods we've found are:
Traverse all GameObjects and check if transform.parent == null... This is very slow since we have a lot of child transforms.
Keep track of which GameObjects are roots and add a root tag appropriately (then find them using GameObjects.FindObjectsWithTag).
Is there a more elegant way of finding all root transforms in the scene hierarchy?
I really want to know this also. Especially when the GameObjects are inactive, we can't normally find them. How can we traverse through thousands of GOs just to find several root GameObject ? I know that Resource.FindObjectsOfTypeAll should do the trick but it's terribly slow, why should I search the whole project just to find several root scene object ? Anyone have a better idea ?
Answer by DonKanallie · Jan 15, 2016 at 08:42 AM
With a recent Unity version (around 5.3) the preferred way would be
UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects()
Seems that method .GetRootGameObjects() not found in Unity 5.3.1, are they removed it ? :(
Available since 5.3.2 http://unity3d.com/ru/unity/whats-new/unity-5.3.2
Answer by sparkzbarca · Nov 06, 2012 at 04:34 AM
no of course there is no way to quickly search thousands of things for a few specific things.
However its worth asking yourself how these objects get generated to begin with.
If these roots are really important to you you have a few choices.
Search during load and store the result (lets be clear here, once you find these objects or any really you store them in a variable so you dont have to run another search again, that is irregardless of the way you search)
Store them during generation, it seems to me that when a parent is created you should simply shuttle it off to an array of transforms for later access. Is there a reason this isn't viable?
keep in mind even if the parents are changing its probably less costly to mess with a small array that search a large scene.
Maybe you should explain your issue in more detail and we can help you come up with an alternative way of doing something. You said each parent has lots of children, maybe thats not a good approach. It does for example result in tons of things waking up all at once on a movement. If you explained the larger context it might be that you dont in fact need what you think you need.
Your answer
Follow this Question
Related Questions
How can I find a unique sibling/parent/child in a specific hierarchy and not from all the scene? 1 Answer
find next gameobject in hierarchy? 1 Answer
How to find which script disables my gameobject 1 Answer
How to get a recursive named bone transform? 3 Answers
GetComponent - Root Hierachy 2 Answers