Search Unity

4.6 uGUI Hierarchy Z Sort

Discussion in 'Immediate Mode GUI (IMGUI)' started by rakkarage, Aug 1, 2014.

  1. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    i got an interface here that depends on z order
    i was wondering if and how something like this would be possible with the new uGUI since z order is ignored?
    thanks

    i guess each window needs to be a world space canvas?
     
    Last edited: Aug 1, 2014
  2. ruetaitbout

    ruetaitbout

    Joined:
    Aug 29, 2014
    Posts:
    2
    If you put this script on the canvas object, it will bubble-sort the elements in the canvas, changing the order of the canvas children. (I'm comparing position.z's here, but you can use any criteria)

    Code (CSharp):
    1. int k = transform.childCount;
    2. Transform childI;
    3. Transform childJ;
    4.  
    5. for( int i = 0; i < k; i++ ){
    6.  
    7.     for( int j = 0; j < k; j++ ){
    8.      
    9.         if( i == j )
    10.             continue;
    11.  
    12.         childI = transform.GetChild( i );
    13.         childJ = transform.GetChild( j );
    14.  
    15.         if( childI.position.z > childJ.position.z ){
    16.  
    17.             int tempIndex = childJ.GetSiblingIndex();
    18.  
    19.             childJ.SetSiblingIndex( childI.GetSiblingIndex() );
    20.             childI.SetSiblingIndex( tempIndex );
    21.  
    22.         }
    23.      
    24.     }
    25.  
    26. }
     
    Birkeman and rakkarage like this.
  3. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    thanks. i recently got it to work like this.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Linq;
    3. public static class GameObjectExtensions
    4. {
    5.     public static void SortChildren(this GameObject gameObject)
    6.     {
    7.         var children = gameObject.GetComponentsInChildren<Transform>(true);
    8.         var sorted = from child in children
    9.                      orderby child.gameObject.activeInHierarchy descending, child.localPosition.z descending
    10.                      where child != gameObject.transform
    11.                      select child;
    12.         for (int i = 0; i < sorted.Count(); i++)
    13.         {
    14.             sorted.ElementAt(i).SetSiblingIndex(i);
    15.         }
    16.     }
    17. }
    18.  
     
    Last edited: Sep 5, 2014
  4. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    i am using a single Screen Space Camera Canvas instead of a bunch of World Canvases as i expected...

    the sorting would be easier with world space but then stretching to screen and reference resolution do not work i guess
     
    Last edited: Sep 5, 2014