Search Unity

Question Is not guaranteed the child index(order) of transform?

Discussion in 'Editor & General Support' started by MrSions, Feb 14, 2024.

  1. MrSions

    MrSions

    Joined:
    Sep 25, 2020
    Posts:
    3
    I was told that the order of the children in Hierarchy is not guaranteed at release build.


    I think there are only below cases where the order is not guaranteed.
    - Scene's root objects.
    - Another code modified Transform index in advance.


    I think the child order of Transform is guaranteed.

    for example, UGUI.

    UGUI is designed to draw ui based on the order of children.

    I don't think the UGUI team developed this issue without knowing it.

    Also I've never seen a problem with the order in which it's drawn so far.



    ---------------------------------------------------------------------------------------
    Heard story.

    CODES
    Code (CSharp):
    1. public class PlayerBehaviour : MonoBehaviour
    2. {
    3. }
    4.  
    5. public class GameManager : MonoBehaviour
    6. {
    7.     private void Awake()
    8.     {
    9.         var player = transform.GetChild(3).GetComponent<PlayerBehaviour>();
    10.         if (player)
    11.         {
    12.             print("Exists");
    13.         }
    14.         else
    15.         {
    16.             print("Not found");
    17.         }
    18.     }
    19. }
    20.  
    HIERARCY
    capture.png

    RESULT
    Most of the time, the "Not found" message
    and the results were different for each build.
    --------------------------------------------------------------------------------------------



    But I found this answer -> indexors on Transform

    Is it true?
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,859
    You've linked a post from 2007, so things have very likely changed within the 17 years since then. I'm pretty sure child transform order is guaranteed, as is the order of components nowadays as well.

    As always, do your own testing to confirm this.
     
  3. MrSions

    MrSions

    Joined:
    Sep 25, 2020
    Posts:
    3

    I tested this, of course. I tested it in the 2022 version. I've done 10 builds and all the results are guaranteed Transform index as I expected.

    But what I heard is that Transform index was not guaranteed in the 2019 version.

    And the friend who said it said he saw the official position of Unity.
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,859
    It's possible that it changed at some point. Once upon a time component order was not guaranteed, but that got changed to support certain features (particularly for Audio). The same is possible for transform child order.

    Mind you the code in your example is not code you should ever actually write. There are much better ways to find specific components among children game objects.