- Home /
Iterating through children of transform: is there an order guarantee?
If I iterate through the children of a transform with a foreach loop, is there any guarantee for the order in which the children are enumerated?
E.g. if I set up a test scene with the following hierarchy:
And then I use a foreach loop to iterate through the children of "Cube":
foreach(Transform child in this.transform)
Debug.Log(child.name);
What happens is that A B C D is always printed in alphabetical order. Is this a guarantee though? An alphabetical-order traversal isn't defined in the documentation for Transform.
The reason why I ask is because I am iterating over multiple transform hierarchies that have an identical structure, and it would be nice to know if there is some sort of order guarantee when iterating through children.
Answer by whydoidoit · Jun 28, 2012 at 08:53 PM
I don't think there is a guarantee and if there is an order it would more likely to be the order that you added them.
You could guarantee your own order like this:
using System.Linq;
using System.Collections.Generic;
...
foreach(var child in transform.Cast<Transform>().OrderBy(t=>t.name))
{
}
There is indeed no guaranteed order. If there's none mentioned, you can assume that there isn't any. (In fact there's no guaranteed order for anything in Unity that involves arrays.)
Most people would want and expect the order they added them. I found the answer in another post:
foreach (var child in parentTransform.Cast<Transform>().OrderBy(t => t.GetSiblingIndex()))
Answer by MaxLohMusic · Mar 22 at 06:58 AM
You can set the order by order you added them thus
foreach (var child in parentTransform.Cast<Transform>().OrderBy(t => t.GetSiblingIndex()))
Your answer
Follow this Question
Related Questions
Trying to destroy all children, but they don't disappear (no errors) 1 Answer
How do I set a child object to not rotate if the parent WILL be rotating? 1 Answer
Getting transform info after branch 1 Answer
FindChild not working? (Pick up Object) 2 Answers
Transform child object over time and then destroy it. 1 Answer