Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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

Creating text UI Dropdown menus

In the previous recipe, we created radio-style buttons with a Toggle Group to present the user with a choice of one of many options. Another way to offer a range of choices is with a drop-down menu. Unity provides the UI Dropdown control for such menus. In this recipe, we’ll offer the user a drop-down choice for the suit of a deck of cards (hearts, clubs, diamonds, or spades):

Figure 2.37: Checking the drop-down menu in the Console window

Note that the UI Dropdown that’s created by default includes a scrollable area if there isn’t space for all the options. We’ll learn how to remove such GameObjects and components to reduce complexity when such a feature is not required.

How to do it...

To create a UI Dropdown control GameObject, follow these steps:

  1. Create a new Unity 2D project and install TextMeshPro by choosing: Window | TextMeshPro | Import TMP Essential Resources.
  2. Add a UI Dropdown - TextMeshPro to the scene.
  3. In the Inspector window, for the Dropdown (Script) component, change the list of Options from Option A, Option B, and Option C to Hearts, Clubs, Diamonds, and Spades. You’ll need to click the plus (+) button to add space for the fourth option, that is, Spades.
  4. Add an instance of the C# script class called DropdownManager to the Dropdown GameObject:
    using UnityEngine;
    using TMPro;
    public class DropdownManager : MonoBehaviour  {
        private TMP_Dropdown dropdown;
        private void Awake() {
            dropdown = GetComponent<TMP_Dropdown>();
        }
        public void PrintNewValue() {
            int currentValue = dropdown.value;
            print ("option changed to = " + currentValue);
       }
    }
    
  5. With the Dropdown GameObject selected, add an On Value Changed event to the list of event handlers for the Dropdown (Script) component, click on the plus (+) button to add an event handler slot, and drag Dropdown into the Object slot.
  6. From the Function drop-down menu, choose DropdownManager and then choose the PrintNewValue method.
  7. Save and run the scene. Each time you change Dropdown, the On Value Changed event will fire, and you’ll see a new text message is printed to the Console window by our script, stating the Integer index of the chosen Dropdown value (0 for the first item, 1 for the second item, and so on).
  8. Select the Template child GameObject of Dropdown in the Project window and, in its Rect Transform panel, reduce its height to 50. When you run the scene, you should see a scrollable area, since not all options fit within the template’s height:

Figure 2.38: Example of a drop-down menu

  1. Delete the Scrollbar child of the Template GameObject and remove the Scroll Rect (Script) component of it. When you run the scene now, you’ll only see the first two options (Hearts and Clubs), with no way to access the other two options. When you are sure your template’s height is sufficient for all its options, you can safely remove these scrollable options to simplify the GameObjects in your scene.

How it works...

When you create a Unity UI DropDown-TextMeshPro GameObject, it comes with several components and child GameObjects – Label, Arrow, and Template (as well as ViewPort and Scrollbar, and so on). Dropdowns work by duplicating the Template GameObject for each of the options listed in the Dropdown (Script) component. Both the Text and Sprite image values can be given for each option. The properties of the Template GameObject are used to control the visual style and behavior of the dropdown’s thousands of possible settings.

First, you replaced the default options (Option A, Option B, and so on) in the Dropdown (Script) component. You then created a C# script class called DropdownManager, which, when attached to your dropdown and having its PrintNewValue method registered for On Value Changed events, means you can see the Integer index of the option each time the user changes their choice. Item index values start counting at zero (as is the case in many computing contexts), so 0 for the first item, 1 for the second item, and so on.

Since the default Dropdown GameObject that was created includes a Scroll Rect (Script) component and a Scrollbar child GameObject, when you reduced the height of Template, you could still scroll through the options. You then removed these items so that your dropdown didn’t have a scrolling feature anymore.

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