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?

With a recent Unity version (around 5.3) the preferred way would be

UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects()

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.

  1. 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)

  2. 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.

  1. 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.