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 related radio buttons using UI Toggles

Unity UI Toggles are also the base components if we wish to implement a group of mutually exclusive options in the style of radio buttons. We need to group related radio buttons together (UI Toggles) to ensure that when one radio button turns on (is selected), all the other radio buttons in the group turn off (are unselected).

We also need to change the visual look if we want to adhere to the usual style of radio buttons as circles, rather than the square UI Toggle default images:

A screenshot of a computer

Description automatically generated

Figure 2.33: Example of three buttons with Console status

Getting ready

For this recipe, we have prepared the images that you’ll need in a folder named UI Demo Textures in the 02_11 folder.

How to do it...

To create related radio buttons using UI Toggles, do the following:

  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. Import the UI Demo Textures folder into the project.
  4. Add a UI Toggle to the scene, naming this new GameObject Toggle-easy.
  5. For the Label child of the Toggle-easy GameObject, set the Text property to Easy.
  6. Select the Canvas GameObject and, in the Inspector window, add a UI | Toggle Group component.
  7. With the Toggle-easy GameObject selected, in the Inspector window, drag the Canvas GameObject into the Toggle Group property of the Toggle (Script) component.
A screenshot of a computer

Description automatically generated

Figure 2.34: Assigning the Canvas Toggle Group to the Toggle-easy GameObject

  1. Assign the Toggle-easy GameObject with a new Tag called Easy. Do this by selecting Add Tag… from the Tag drop-down menu in the Inspector window – this will open the Tags & Layers panel. Click the plus (+) button for a new Tag, and create a new Tag, Easy. Finally, select the Toggle-easy GameObject again in the Hierarchy window, and at the top of the Inspector, set its Tag to Easy.
    A screenshot of a computer

Description automatically generated

    Figure 2.35: Creating new Tag called Easy

    You can also create/edit Tags & Layers from the project Settings panel, accessed from the Edit | Settings… menu.

  1. Select the Background child GameObject of Toggle-easy and, for its Image component, select the UIToggleBG image in the Source Image property (a circle outline).

    To make these toggles look more like radio buttons, the background of each is set to the circle outline image of UIToggleBG, and the checkmark (which displays the toggles that are on) is filled with the circle image called UIToggleButton.

  1. In the Inspector for the Toggle component, ensure the Is On property is checked. Then select the Checkmark child GameObject of Toggle-easy. In the Image component, choose the UIToggleButton image for the Source Image property (a filled circle).

    Of the three choices (easy, medium, and hard) that we’ll offer to the user, we’ll set the easy option to be the one that is supposed to be initially selected. Therefore, we need its Is On property to be checked, which will lead to its checkmark image being displayed.

  1. Add an instance of the RadioButtonManager C# script class to the Canvas GameObject:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    public class RadioButtonManager : MonoBehaviour {
      private string currentDifficulty = "Easy";
      public void PrintNewGroupValue(Toggle sender){
        // only take notice from Toggle just switched to On
        if(sender.isOn){
          currentDifficulty = sender.tag;
          print ("option changed to = " + currentDifficulty);
        }
      }
    }
    
  2. With the Toggle-easy 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 the Canvas GameObject into the Object slot.
  3. Then, from the Function drop-down menu, choose RadioButtonManager and then choose the PrintNewGroupValue method.
  4. Into the Toggle parameter slot, which is initially None (Toggle), drag the Toggle-easy GameObject. This means that the Toggle-easy GameObject calls the PrintNewGroupValue(...) method of a C# scripted component called RadioButtonManager in the Canvas GameObject, passing itself as a parameter.
A graph on a computer screen

Description automatically generated

Figure 2.36: Dragging the Toggle-easy GameObject to the Toggle parameter slot

  1. Duplicate the Toggle-easy GameObject, naming the copy Toggle-medium. Set its Rect Transform property’s Pos Y to -25 (so that this copy is positioned below the easy option) and uncheck the Is On property of the Toggle component. Create a new Tag, Medium, and assign the Tag to the new GameObject, Toggle-medium.
  2. Duplicate the Toggle-medium GameObject, naming the copy Toggle-hard. Set its Rect Transform property’s Pos Y to -50 (so that this copy is positioned below the medium option). Create a new Tag, Hard, and assign the Tag to the new GameObject, Toggle-hard.
  3. Save and run the scene. Each time you check one of the three radio buttons, 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 tag of whichever Toggle (radio button) was just set to true (Is On).

How it works...

By using the UIToggleBG and UIToggleButton images, we made the UI GameObject look like radio buttons – circles that when selected have a filled center. By adding a Toggle Group component to Canvas, and having each Toggle GameObject link to it, the three radio buttons can tell Toggle Group when they have been selected. Then, the other members of the group are deselected.

Each Toggle has an On Value Changed event handler that prints out the Tag for the GameObject. So, by creating the Tags Easy, Medium, and Hard, and assigning them to their corresponding GameObjects, we are able to print out a message corresponding to the radio button that has been clicked by the user.

If you had several groups of radio buttons in the same scene, one strategy is, for each group, to add the Toggle Group component to one of the Toggles and have all the others link to that one. So, all Toggles in each group link to the same Toggle Group component.

Note. We store the current radio button value (the last one switched On) in the currentDifficulty property of the RadioButtonManager component of GameObject Canvas. Since variables declared outside a method are remembered, we could, for example, add a public method, such as GetCurrentDifficulty(), which could tell other scripted objects the current value, regardless of how long it’s been since the user last changed their option.

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