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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With