
Unity Cookbook
By :

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.
Figure 2.31: Example showing the button’s status changing in the Console window
For this recipe, we have prepared the C# script ToggleChangeManager
class in the 02_10
folder.
To display an on/off UI Toggle to the user, follow these steps:
Toggle
GameObject, set the Text property to First Class.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);
}
}
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.
Figure 2.32: Setting the Toggle’s On Value Changed event handler function
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
.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
.