- Home /
Guarantee loop order of child objects.
So now that Unity has a rearrangeable hierarchy, does this mean that the order in which
foreach (Transform t in transform)
{
//DO something
}
will loop through will be the order of the objects in the hierarchy?
I need this because I've made string that consists of many parts. All the parts are childed to a parent. I need to guarantee the order because I'm using a line renderer to render between each part.
Well, after some testing in Unity 5.4.1, yes it will loop in the hierarchy's order.
Unfortunately, just because it does doesn't mean it's guaranteed.
Yes, that's true, but seeing as the UI does depend of the hierarchy's order, we can somewhat safely assume it will, it would be quite convulted for the Unity devs to cycle through children differently for the UI than any other GameObject. Of course, thoses are just assumptions.
Answer by bpears · Dec 16, 2016 at 01:04 AM
You could add a super small script that has no update or start or anything, just a public int variable that you want to assign to the parts, and put that script on each part as a way to index them in order. Then in your actual script, get their scriptable object containing its int index as a component, and have some bools check that it is index 0, then 1, then 2, and repeat the code for each index.
Another way, which is probably better depending on the situation, is just create a public GameObject[] array in your script and assign each piece, in order, and then iterate through them in a loop like this instead:
for(i=0;i<myObjectPieces.Length;i++){
if(i==0){
//process your first piece
//note : the first element in all arrays is always 0, not 1.
}
//and so on
}