Unity UI按钮绑定事件
第一步:通过Hierarchy面板创建button,如图
第二步:创建一个脚本名为TestClick,并定义一个名为Click的public方法
using UnityEngine;
using System.Collections;
public class TestClick : MonoBehaviour {
public void Click()
{
Debug.Log("Button Clicked");
}
}
第三步:选中Button ,Add Component选择TestClick
第四步:关联TestClick中的Click方法,如果然后运行,我们就能看到绑定的事件了
总结一下:需要script的object,这些script就只管控制这些变化,成为一个个方法,用C#的代码来实现。如果调用的话,是需要的按钮,或者控件上面的OnClick事件上面绑定好就行了,一个是绑定object,另外一个是选择执行的函数方法什么的。
虽然已经已经实现对Unity UI新的UI系统如何绑定事件做了大概讲解,但是弊端明显,就是每个UI元素都创建一个MonoBehavior来进行监听各个事件,显然这样做不行,下面我们来学习下利用Delegate和Event来做一个通用类UIEventListener来处理事件(不了解Delegate和Event的童鞋请自行谷歌搜索观察者模式)
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UIEventListener : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler
{
/// <summary>
/// 定义事件代理
/// </summary>
/// <param name="gb"></param>
public delegate void UIEventProxy(GameObject gb);
/// <summary>
/// 鼠标点击事件
/// </summary>
public event UIEventProxy OnClick;
/// <summary>
/// 鼠标进入事件
/// </summary>
public event UIEventProxy OnMouseEnter;
/// <summary>
/// 鼠标滑出事件
/// </summary>
public event UIEventProxy OnMouseExit;
public void OnPointerClick(PointerEventData eventData)
{
if (OnClick != null)
OnClick(this.gameObject);
}
public void OnPointerEnter(PointerEventData eventData)
{
if (OnMouseEnter != null)
OnMouseEnter(this.gameObject);
}
public void OnPointerExit(PointerEventData eventData)
{
if (OnMouseExit != null)
OnMouseExit(this.gameObject);
}
}
调用部分代码
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
// Use this for initialization
void Start()
{
Button btn = this.GetComponent<Button>();
UIEventListener btnListener = btn.gameObject.AddComponent<UIEventListener>();
btnListener.OnClick += delegate(GameObject gb)
{
Debug.Log(gb.name);
};
btnListener.OnMouseEnter += delegate(GameObject gb)
{
Debug.Log(gb.name);
};
btnListener.OnMouseExit += delegate(GameObject gb)
{
Debug.Log(gb.name);
};
}
}