Search code examples
c#unity-game-engineinitialization

Unity - GetComponentsInChildren<T>() return order


I know it returns the given components found in the parent's hierarchy, but by what order? I need to know because I want to use this to initialize my scripts and I have to initialize the parents first and then the children (becasue lower hierarchy components use their direct parents' calculated values).


Solution

  • Unity documentation for GetComponentsInChildren does not guarantee a specific return order -- thus even if you find a deterministic order in the current version it's liable to break when Unity ships a new build that changes that deterministic order. Thus, you'll need to enforce the parent-initialization-first guarantees in your own code. One way to do this would be to iterate over the transform:

    void InitializeHierarchy(Transform root)
    {
        var initializable = root.GetComponent<Initializable>();
        if(initializable != null) initializable.Initialize();
        foreach(Transform t in root)
        {
            if(t == root) continue;  //make sure you don't initialize the existing transform
            InitializeHierarchy(t); //initialize this Transform's children recursively
        }
    }
    

    Note: this will initialize direct parents before direct children -- however it will NOT initialize aunts/uncles before nieces/nephews.