Toggles and radio buttons via Toggle Groups

Users make choices, and often, these choices are either to have one of two available options (for example, sound on or off), or sometimes to choose one of several possibilities (for example, difficulty level easy/medium/hard). Unity UI Toggles allows users to turn options on and off; and when combined with Toggle Groups, they restrict choices to one of the group of items. In this recipe, we'll first explore the basic Toggle, and a script to respond to a change in values. Then in the There's More section, we'll extend the example to illustrate Toggle Groups, and styling these with round images to make them look more like traditional radio buttons.

The following screenshot shows how the button's status changes are logged in the Console panel when the scene is running:

Toggles and radio buttons via Toggle Groups

Getting ready

For this recipe, we have prepared the images that you'll need in a folder named UI Demo Textures in the 1362_01_15 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.
  2. In the Inspector panel, change the Background color of the Main Camera to white.
  3. Add UI Toggle to the scene.
  4. Enter First Class as Text for the Label child GameObject of the Toggle GameObject.
  5. Add an instance of the C# script class called ToggleChangeManager to the Toggle GameObject:
    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class ToggleChangeManager : MonoBehaviour {
      private Toggle toggle;
    
      void Start () {
        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.
  7. From the Function drop-down menu, choose ToggleChangeManager and then choose the PrintNewToggleValue method.
  8. 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 the Toggle.

How it works...

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

The C# scripted class called ToggleChangeManager's method called Start() gets 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 to change its value, an On Value Changed event is fired. We then register the PrintNewToggleValue()method, which is supposed to be executed when such an event occurs. This method retrieves, and then prints out to the Console panel the new Boolean true/false value of the Toggle.

There's more...

There are some details that you don't want to miss.

Adding more Toggles and a Toggle Group to implement mutually-exclusive radio buttons

The 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. To create such a group of related choices, do the following:

  1. Import the UI Demo Textures folder into the project.
  2. Remove the C# script class ToggleChangeManager component from the Toggle GameObject.
  3. Rename the Toggle GameObject as Toggle-easy.
  4. Change the Label text to Easy, and tag this GameObject with a new tag called Easy.
  5. Select the Background child GameObject of Toggle-easy, and in the Image (Script) component, drag the UIToggleBG image into the Source Image property.
  6. Ensure that the Is On property of the Toggle (Script) component is checked, and then select the Checkmark child GameObject of Toggle-easy. In the Image (Script) component, drag the UIToggleButton image into the Source Image property.

    Note

    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.

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

  7. Duplicate the Toggle-easy GameObject, naming the copy Toggle-medium. Set its Rect Transform property Pos Y to -25 (so, this copy is positioned below the easy option), and uncheck the Is On property of the Toggle (Script) component. Tag this copy with a new tag called Medium.
  8. Duplicate the Toggle-medium GameObject, naming the copy Toggle-hard. Set its Rect Transform property Pos Y to -50 (so this copy is positioned below the medium option). Tag this copy with a new tag called Hard.
  9. Add an instance of the C# script class called RadioButtonManager 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 swtiched to On
        if(sender.isOn){
          currentDifficulty = sender.tag;
          print ("option changed to = " + currentDifficulty);
        }
      }
    }
  10. 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.
  11. From the Function drop-down menu, choose RadioButtonManager, and then choose the PrintNewGroupValue method. In the Toggle parameter slot, which is initially None (Toggle), drag the Toggle-easy GameObject.
  12. Do the same for the Toggle-medium and Toggle-hard GameObjects—so each Toggle object calls the PrintNewGroupValue(…)method of a C# scripted component called RadioButtonManager in the Canvas GameObject, passing itself as a parameter.
  13. 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).
  14. The following screenshot shows how the value corresponding to the selected radio button is logged to the Console panel when the scene is running:
    Adding more Toggles and a Toggle Group to implement mutually-exclusive radio buttons
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.103