Version: 2018.4
LanguageEnglish
  • C#

Toggle.onValueChanged

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public UI.Toggle.ToggleEvent onValueChanged;

Description

Callback executed when the value of the toggle is changed.

Use this to detect when a user activates or deactivates the Toggle. Add a listener to perform an action when this Event detects a change in the Toggle state. See the delegates tutorial for more information on delegates.

//Attach this script to a Toggle GameObject. To do this, go to Create>UI>Toggle.
//Set your own Text in the Inspector window

using UnityEngine; using UnityEngine.UI;

public class Example : MonoBehaviour { Toggle m_Toggle; public Text m_Text;

void Start() { //Fetch the Toggle GameObject m_Toggle = GetComponent<Toggle>(); //Add listener for when the state of the Toggle changes, to take action m_Toggle.onValueChanged.AddListener(delegate { ToggleValueChanged(m_Toggle); });

//Initialise the Text to say the first state of the Toggle m_Text.text = "First Value : " + m_Toggle.isOn; }

//Output the new state of the Toggle into Text void ToggleValueChanged(Toggle change) { m_Text.text = "New Value : " + m_Toggle.isOn; } }