- Home /
Changing UGUI sorting layer via script
I am aware that it is possible to change the sorting layer in the order of hierarchy ordering, but i need to change the order layer of the ui in runtime so that whenever I rotate a panel 180 degrees the other panel in the back of that panel will be shown above since it has a closer z axis to the camera. How may I do this?
Answer by deeds0l · Apr 06, 2015 at 07:28 AM
I figured out that you can attach a Canvas component to the UI object and override its main parent's sorting layer there.
Answer by asafsitner · Jan 08, 2015 at 08:41 AM
Since the order of the hierarchy is the order of drawing, Unity has provided us with a neat API calls to sort hierarchy elements. Take a look at the following:
SetParent
SetAsFirstSibling
SetAsLastSibling
With these, you can call - for example - SetAsLastSibling on the panel you want to move to the front, since uGUI draws elements from first to last so the last element is drawn above the others. Note that this happens regardless of z-depth, it doesn't matter when it comes to uGUI.
yes this is a good work around but I would need my child panel to be layered on top of its parent how may I do this?
Something like this?
childPanel.SetParent(childPanel.parent.parent);
childPanel.SetAsLastSibling();
Thanks for the idea but the problem with that is that it resizes the childPanel which I am moving around. How could i keep the current rect scale and position as I move it around?
The API documentation of SetParent mentions an overload (well not exactly an overload, looks more like a default false value on worldPositionStays but it behaves more or less the same for this purpose) for keeping the scale, rotation and position the same after changing the parent, like so:
childPanel.SetParent(childPanel.parent.parent, true);
Notice the additional true parameter sent to the method - this is the option to make the transform keep its world scale, rotation, and position after switching parent.
The problem with this is that it does not really keep my scale but it follows the anchor point of the childPanel and still rescales it.
Your answer