While Rect Transform offers SetAsLastSibling (move to front) and SetAsFirstSibling (move to back), and even SetSiblingIndex (if we knew exactly what position in the sequence to type in), there isn't a built-in way to make an element move up or down just one position in the sequence of GameObjects in the Hierarchy window. However, we can write two straightforward methods in C# to do this, and we can add buttons to call these methods, providing full control of the top-to-bottom arrangement of the UI controls on the screen. To implement four buttons (move-to-front/move-to-back/up one/down one), do the following:
- Create a C# script class called ArrangeActions containing the following code and add an instance as a scripted component to each of your UI Panels:
using UnityEngine; public class ArrangeActions : MonoBehaviour { private RectTransform panelRectTransform; void Awake() { panelRectTransform = GetComponent<RectTransform>(); } public void MoveDownOne() { int currentSiblingIndex = panelRectTransform.GetSiblingIndex(); panelRectTransform.SetSiblingIndex( currentSiblingIndex - 1 ); } public void MoveUpOne() { int currentSiblingIndex = panelRectTransform.GetSiblingIndex(); panelRectTransform.SetSiblingIndex( currentSiblingIndex + 1 ); } }
- Add a second UI Button to each card panel, this time using the arrangement triangle icon image called icon_move_to_back, and set the OnClick event function for these buttons to SetAsFirstSibling.
- Add two more UI Buttons to each card panel with the up and down triangle icon images; that is, icon_up_one and icon_down_one. Set the OnClick event handler function for the down-one buttons to call the MoveDownOne() method, and set the functions for the up-one buttons to call the MoveUpOne() method.
- Copy one of the UI Panels to create a third card (this time showing the Ace of diamonds). Arrange the three cards so that you can see all four buttons for at least two of the cards, even when those cards are at the bottom (see the screenshot at the beginning of this recipe).
- Save the scene and run your game. You will now have full control over how to layer the three card UI Panels.
Note that we should avoid negative sibling depths, so we should probably test for the currentSiblingIndex value before subtracting 1 as follows:
if(currentsiblingIndex > 0)
panelRectTransform.SetSiblingIndex( currentSiblingIndex - 1 );