I need to have elements in the canvas change their display order (depth) from a script (C#). Since that order is now determined by the placement in the Hierarchy, how do I do that?
hu90
2
You have to change their order in the hierarchy indeed.
For example, this function will move the attached transform within its parent transform by delta positions (positive is forward, negative is backwards) :
public void MoveInHierarchy(int delta) {
int index = transform.GetSiblingIndex();
transform.SetSiblingIndex (index + delta);
}
A typical real world example is, say you have a number of buttons. When any one is clicked, you’re going to bounce animate it, so it becomes much bigger for a half second. The one being bounced must be ahead of all the rest in z-order, or the overlap won’t look good.
Fortunately it’s this easy
private IEnumerator _bounce(int whichButton)
{
// be sure to bring it to the "front" of its siblings
RectTransform moveToFront =
buttons[whichButton].GetComponent<RectTransform>();
moveToFront.SetSiblingIndex( buttons.Length - 1 );
... bounce the button 'whichButton'
}
This is the very reason Unity added these “sibling order related” calls.
Note that often, you can just use SetAsLastSibling , even easier!
_dns
3
Hi,
You can use all the “sibling” named functions of the Transform component: Unity - Scripting API: Transform
You can now add a Canvas and change the Sort Order parameter.
I have had a similar issue, SetAsLastSibling() worked for me!