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

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.

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 €18.99/month. Cancel anytime