How to change the order of child objects in sortingGroup

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 :slight_smile:

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.

Transform textTransform = transform.Find("text");

if (textTransform)
{
     textTransform.SetSiblingIndex(1);
             
      // and the following works too
      //textTransform.parent = null;
      //text.transform.parent = this.transform;
}
10 Likes

You could also use

To move one child to the bottom or, the other one to move it to the top

10 Likes

Thanks! This still works in 2021 for ordering UI elements. Very helpful when generating elements from script.