描述Button之前,首先要知道Selectable组件,Selectable组件描述了交互过程中样式的变化。如图:
因此在Button的Inspector中,你也可以看到这些内容。另外Button额外定义了按钮点击事件
[AddComponentMenu("UI/Button", 30)]
public class Button : Selectable, IPointerClickHandler, IEventSystemHandler, ISubmitHandler
{
protected Button();
public ButtonClickedEvent onClick { get; set; }
public virtual void OnPointerClick(PointerEventData eventData);
public virtual void OnSubmit(BaseEventData eventData);
public class ButtonClickedEvent : UnityEvent
{
public ButtonClickedEvent();
}
}
针对onClick这个UnityEvent,我们添加响应可以直接在Inspector界面中添加,或者在脚本中手动添加:
void Start()
{
string s = "Button Clicked";
GetComponent<Button>().onClick.AddListener(() => OnClick(s));
}
void OnClick(string s)
{
Debug.Log(s);
GetComponent<Image>().color = Color.red;
}