Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-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.
undefined
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 ₹800/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy