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

Detecting interactions with a single Toggle UI component

Users make choices and, often, these choices have one of two options (for example, sound on or off), or sometimes one of several possibilities (for example, difficulty level as easy/medium/hard). Unity UI Toggles allows users to turn options on and off; when combined with toggle groups, they restrict choices to one of the groups of items.

In this recipe, we’ll explore the basic Toggle and a script to respond to a change in values.

A screenshot of a computer

Description automatically generated

Figure 2.31: Example showing the button’s status changing in the Console window

Getting ready

For this recipe, we have prepared the C# script ToggleChangeManager class in the 02_10 folder.

How to do it...

To display an on/off UI Toggle to the user, follow these steps:

  1. Create a new Unity 2D project and install TextMeshPro by choosing: Window | TextMeshPro | Import TMP Essential Resources.
  2. In the Inspector window, change the Background color of Main Camera to white.
  3. Add a UI Toggle to the scene.
  4. For the Label child of the Toggle GameObject, set the Text property to First Class.
  5. Add an instance of the C# script class called ToggleChangeManager to the Toggle GameObject:
    using UnityEngine;
    using UnityEngine.UI;
    public class ToggleChangeManager : MonoBehaviour {
       private Toggle toggle;
       void Awake () {
             toggle = GetComponent<Toggle>();   
       }
       public void PrintNewToggleValue() {
             bool status = toggle.isOn;
             print ("toggle status = " + status);
       }
    }
    
  6. With the Toggle GameObject selected, add an On Value Changed event to the list of event handlers for the Toggle (Script) component, click on the plus (+) button to add an event handler slot, and drag Toggle into the Object slot.

    Note. If this is the first time you have done this, it may seem strange to select a GameObject, and then drag this same GameObject into a property of one of its components. However, this is quite common, since the logic location for behavior like button actions and scripted actions is a component of the GameObject whose behavior is being set. So, it is correct to drag the Toggle GameObject into the Object slot for that toggle’s On Value Changed event handler.

  1. From the Function drop-down menu, choose ToggleChangeManager and then choose the PrintNewToggleValue method.
A screenshot of a computer

Description automatically generated

Figure 2.32: Setting the Toggle’s On Value Changed event handler function

  1. Save and run the scene. Each time you check or uncheck the Toggle GameObject, the On Value Changed event will fire, and you’ll see a new text message printed into the Console window by our script, stating the new Boolean true/false value of Toggle.

How it works...

When you create a Unity UI Toggle GameObject, it comes with several child GameObjects automatically – Background, Checkmark, and the text’s Label. Unless we need to style the look of a Toggle in a special way, all we must do is simply edit the text’s Label so that the user knows what option or feature this Toggle is going to turn on/off.

The Awake() method of the ToggleChangeManager C# class caches a reference to the Toggle component in the GameObject where the script instance is located. When the game is running, each time the user clicks on the Toggle component to change its value, an On Value Changed event is fired. Then, we register the PrintNewToggleValue() method, which is to be executed when such an event occurs. This method retrieves, and then prints out to the Console window, the new Boolean true/false value of Toggle.

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 €14.99/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