Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity Cookbook

You're reading from   Unity Cookbook Over 160 recipes to craft your own masterpiece in Unity 2023

Arrow left icon
Product type Paperback
Published in Nov 2023
Publisher Packt
ISBN-13 9781805123026
Length 780 pages
Edition 5th Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Sinéad Murphy Sinéad Murphy
Author Profile Icon Sinéad Murphy
Sinéad Murphy
Matt Smith Matt Smith
Author Profile Icon Matt Smith
Matt Smith
Shaun Ferns Shaun Ferns
Author Profile Icon Shaun Ferns
Shaun Ferns
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Displaying Data with Core UI Elements 2. Responding to User Events for Interactive UIs FREE CHAPTER 3. Inventory and Advanced UIs 4. Playing and Manipulating Sounds 5. Textures, Materials, and 3D Objects 6. Creating 3D Environments with Terrains 7. Creating 3D Geometry with ProBuilder 8. 2D Animation and Physics 9. Animated Characters 10. Saving and Loading Data 11. Controlling and Choosing Positions 12. Navigation Meshes and Agents 13. Cameras, Lighting, and Visual Effects 14. Shader Graphs and Video Players 15. Particle Systems and Other Visual Effects 16. Mobile Games and Applications 17. Augmented Reality (AR) 18. Virtual and Extended Reality (VR/XR) 19. Advanced Topics – Gizmos, Automated Testing, and More 20. Other Books You May Enjoy
21. Index

Organizing image panels and changing panel depths via buttons

UI Panels are provided by Unity to allow UI controls to be grouped and moved together, and also to visually group elements with an image background (if desired). The sibling depth is what determines which UI elements will appear above or below others. We can see the sibling depth explicitly in the Hierarchy window, since the top-to-bottom sequence of UI GameObjects in the Hierarchy window sets the sibling depth. So, the first item has a depth of 1, the second has a depth of 2, and so on. The UI GameObjects with larger sibling depths (further down the hierarchy, which means they’re drawn later) will appear above the UI GameObjects with smaller sibling depths:

Figure 2.13: Example of organizing panels

In this recipe, we’ll begin by creating two UI Panels, each showing a different playing card image, and we’ll use one button to move between them. We’ll then expand the recipe by creating one more UI Panel. We’ll also add four triangle arrangement buttons to change the display order (move to bottom, move to top, move up one, and move down one).

Getting ready

For this recipe, we have prepared the images that you need in a folder named Images/ornamental_deck-png and Images /icons in the 02_04 folder.

How to do it...

To create the UI Panels whose layering can be changed by clicking buttons, follow these steps:

  1. Create a new Unity 2D project and install TextMeshPro by choosing: Window | TextMeshPro | Import TMP Essential Resources.
  2. Create a new UI Panel GameObject named Panel-jack-diamonds. Do the following to this panel:
    • For the Image (Script) component, drag the jack_of_diamonds playing card image asset file from the Project window into the Source Image property. Select the Color property and increase the Alpha value to 255 (so that this background image of the panel is no longer partly transparent).
    • For the Rect Transform property, position it in the middle-center part of the screen and set its Width to 200 and its Height to 300.
  3. Create a UI Button-TextMeshPro GameObject named Button-move-to-front. In the Hierarchy window, make this button a child of Panel-jack-diamonds. Delete the Text child GameObject of this button (since we’ll use an icon to indicate what this button does).
  4. With the Button-move-to-front GameObject selected in the Hierarchy window, do the following in the Inspector window:
    • In Rect Transform, position the button at the top-center of the player card image so that it can be seen at the top of the playing card. Size the image to Width = 16 and Height = 16. Move the icon image down slightly, by setting Pos Y = -5 (to ensure we can see the horizontal bar above the triangle).
    • For the Source Image property of the Image (Script) component, select the arrangement triangle icon image; that is, icon_move_to_front.
    • Add an OnClick event handler by clicking on the plus (+) sign at the bottom of the Button (Script) component.
    • Drag Panel-jack-diamonds from the Hierarchy window over to the Object slot (immediately below the menu saying Runtime Only).
    • Select the RectTransform.SetAsLastSibling method from the drop-down function list (initially showing No Function):
    A screenshot of a computer

Description automatically generated

    Figure 2.14: Addition of an OnClick event handler

  5. Repeat step 2 to create a second panel named Panel-2-diamonds with its own move-to-front button and a Source Image of 2_of_diamonds. Move and position this new panel slightly to the right of Panel-jack-diamonds, allowing both move-to-front buttons to be seen.
  6. Save your scene and run the game. You will be able to click the move-to-front button on either of the cards to move that card’s panel to the front. If you run the game with the Game window not maximized, you’ll actually see the panels changing the order in the list of the children of Canvas in the Hierarchy window.

How it works...

In this recipe, you created two UI Panels, each of which contains a background image of a playing card and a UI Button whose action will make its parent panel move to the front. You set the Alpha (transparency) setting of the background image’s Color setting to 255 (no transparency).

You then added an OnClick event handler to the button of each UI Panel. This action sends a SetAsLastSibling message to the button’s panel parent. When the OnClick message is received, the clicked panel is moved to the bottom (end) of the sequence of GameObjects in the Canvas, so this panel is drawn last from the Canvas objects. This means that it appears visually in front of all the other GameObjects.

The button’s action illustrates how the OnClick function does not have to be calling a public method of a scripted component of an object, but it can be sending a message to one of the non-scripted components of the targeted GameObject. In this recipe, we send the SetAsLastSibling message to the Rect Transform component of the panel where the button is located.

There’s more...

There are some details you don’t want to miss.

Moving up or down by just one position, using scripted methods

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:

  1. 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() {
    		print("(before change) " + gameObject.name + " sibling index = " + panelRectTransform.GetSiblingIndex());
    		int currentSiblingIndex = panelRectTransform.GetSiblingIndex();
    		if (currentSiblingIndex > 0) {}
    			panelRectTransform.SetSiblingIndex(currentSiblingIndex - 1);
    		}
    		print("(after change) " + gameObject.name + " sibling index = " + panelRectTransform.GetSiblingIndex());
    	}
    	
    	public void MoveUpOne() {
    		print ("(before change) " + gameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
    		
    		int currentSiblingIndex = panelRectTransform.GetSiblingIndex();
    		int maxSiblingIndex = panelRectTransform.childCount - 1;
    		if (currentSiblingIndex < maxSiblingIndex) {
    			panelRectTransform.SetSiblingIndex(currentSiblingIndex + 1);
    		}
    		print ("(after change) " + gameObject.name +  " sibling index = " + panelRectTransform.GetSiblingIndex());
    	}
    }
    
  2. 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.
  3. 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 function for the up-one buttons to call the MoveUpOne() method.
  4. 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).
  5. Save the scene and run your game. You will now have full control over how to layer the three card UI Panels.

Note that the MoveDownOne() and MoveUpOne() methods subtract and add 1 to the sibling depth of the panel the scripted object is a component of. The methods contain a test, so ensure we don’t try to set a negative panel depth or a depth that is higher than the maximum index for the number of panels.

You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023
Publisher: Packt
ISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime