Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Getting children elements in order

Discussion in 'UGUI & TextMesh Pro' started by IntDev, Sep 11, 2014.

  1. IntDev

    IntDev

    Joined:
    Jan 14, 2013
    Posts:
    152
    Regarding UI elements, I'd like to know if using gameObject.transform.GetChild(i) will (or should) give the elements in display order (as you order in the hiearchy). I had some weird behavior, like I had a grid layout with 5 elements and GetChild(0) returned the 5th element.
     
  2. Gizmoi

    Gizmoi

    Joined:
    Jan 9, 2013
    Posts:
    327
    The docs don't state whether GetChild returns based on any ordering system, but you could write an extension that gets all children sorted by sibling index. ref: GetSiblingIndex()
     
  3. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,226
    GetChild should return the proper order so GetChild(0) should be the same object that returns 0 from GetSiblingIndex().

    Just to double check you hierarchy is in transform sort right? its not that you are looking at the wrong ordering?
     
  4. IntDev

    IntDev

    Joined:
    Jan 14, 2013
    Posts:
    152
    @phil-Unity I thought UI elements ignore the transform sort because you sort them in the hierachy view (up elements render behind, bottom element render in front). Btw, I didnt know I can change the transform sort.
     
  5. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,226
    Well changing the order in the hierarchy (when in transform sort) also changes the data in the back end. So hierarchy view (in transform sort) is the proper order.

    Yes you can change out of transform sort into alphanumeric sort if you enable it in Editor preferences (or write your own script see http://docs.unity3d.com/ScriptReference/BaseHierarchySort.html)
     
  6. UnityIsTheBest

    UnityIsTheBest

    Joined:
    Jul 18, 2015
    Posts:
    11
    @phil-Unity Will the following work the exact same?

    Code (CSharp):
    1. foreach (Transform item in transform)
    2.     Debug.Log(item.gameObject.name);
    3.  
    4. for (int i = 0; i < transform.childCount; i++)
    5.     Debug.Log(transform.GetChild(i).gameObject.name);
    Do both always return the topmost one in the Hierarchy view first?
     
  7. phil-Unity

    phil-Unity

    Unity UI Lead Developer Unity Technologies

    Joined:
    Nov 23, 2012
    Posts:
    1,226
    Assuming you dont have Alphanumeric ordering turned on yes should be topmost hierarchy order first.
     
    Sanghyeok0298 and UnityIsTheBest like this.
  8. UnityIsTheBest

    UnityIsTheBest

    Joined:
    Jul 18, 2015
    Posts:
    11
    Thank you!