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?
4 Answers
4You 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!
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!
Thank you very much!
– Amazing_BluieHow can I only just rearrange the first parent's and it's childs' position. Right now its moving the whole entire canvas for me. Please let me know. Thank you.
– TaomujwDDubois - there are no performance concerns whatsoever. It's a game engine - it is constantly rendering massive amounts of mesh, lighting, etc. You use the call in question all the time. It's only something you use when (say) a button is pressed or some action happens - it might be used a few times per hour of play. It's a non-issue.
– Fattie