当开关的值发生更改时执行的回调。
可以用来检测用户激活或停用 Toggle 的时间。添加一个监听器,当此 Event 检测到 Toggle 状态更改时执行操作。请参阅委托教程了解有关委托的更多信息。
//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; } }