Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to change the order of child objects in sortingGroup

Discussion in 'Scripting' started by AnalogUniverse, Dec 4, 2018.

  1. AnalogUniverse

    AnalogUniverse

    Joined:
    Aug 10, 2018
    Posts:
    64
    Hi All

    I have a GameObject "Button" which includes the sortingGroup Component [RequireComponent(typeof(SortingGroup))] the Button has two child objects Background and Text, I have an editor script which destroys and recreates these two child Objects with the following inspector options

    bool "Include text" destroys or creates the text Object accordingly

    and Sprite "idle Image" changing the idleImage sprite destroys the background object and recreates it with a newly calculated collider to match the Sprite size and shape

    Now All works great but depending on what order you change those two inspector properties sometimes the text appears behind the background, so how do I change the order of the child Objects so the background always appears behind the text, Ive checked the documentation for SortingGroup but cant find any properties of methods which change the child Objects order, unless Im missing something. Whats the best way to do this ?

    Thanks :)
     
  2. AnalogUniverse

    AnalogUniverse

    Joined:
    Aug 10, 2018
    Posts:
    64
    OK I think Ive solved it, it appears as if the SortingGroup render order of child objects, is dependant on the order of the siblings in the parents transform (correct me if Im wrong)
    This code placed inside my "include text" method, which is called by the custom inspector, keeps the text on top.

    Code (CSharp):
    1. Transform textTransform = transform.Find("text");
    2.  
    3. if (textTransform)
    4. {
    5.      textTransform.SetSiblingIndex(1);
    6.              
    7.       // and the following works too
    8.       //textTransform.parent = null;
    9.       //text.transform.parent = this.transform;
    10. }
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,186
  4. MichaelEGA

    MichaelEGA

    Joined:
    Oct 11, 2019
    Posts:
    39