
上QQ阅读APP看书,第一时间看更新
How to do it...
To display an on/off UI Toggle to the user, follow these steps:
- Create a new Unity 2D project.
- In the Inspector, change the Background color of the Main Camera to white.
- Add UI Toggle to the scene.
- For the Label child of the Toggle GameObject, set the Text property to First Class.
- 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); } }
- 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.
- From the Function drop-down menu, choose ToggleChangeManager and then choose the PrintNewToggleValue method.
- 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.