参考雨松的博客改写的UGUI 事件监听:http://www.xuanyusong.com/archives/3325;
可以像NGUI 一样用UIEventListener.get().OnClick = 方法;
下面附上代码
using UnityEngine; using UnityEngine.EventSystems; public class UIEventListener : MonoBehaviour, IPointerClickHandler,IPointerUpHandler,IPointerDownHandler,IPointerEnterHandler,IPointerExitHandler,ISelectHandler,IUpdateSelectedHandler { public delegate void VoidDelegate(GameObject go); public delegate void IntDelegate(GameObject go, int index); public VoidDelegate onClick; public IntDelegate onIntClick; public VoidDelegate onDown; public VoidDelegate onEnter; public VoidDelegate onExit; public VoidDelegate onUp; public VoidDelegate onSelect; public VoidDelegate onUpdateSelect; [HideInInspector] private int index; static public UIEventListener Get(GameObject go) { UIEventListener listener = go.GetComponent<UIEventListener>(); if (listener == null) listener = go.AddComponent<UIEventListener>(); return listener; } static public UIEventListener Get(GameObject go, int i) { UIEventListener listener = go.GetComponent<UIEventListener>(); if (listener == null) listener = go.AddComponent<UIEventListener>(); listener.index = i; return listener; } public void OnPointerClick(PointerEventData eventData) { if (onClick != null) onClick(gameObject); else if (onIntClick != null) onIntClick(gameObject, index); } public void OnPointerUp(PointerEventData eventData) { if (onUp != null) onUp(gameObject); } public void OnPointerDown(PointerEventData eventData) { if (onDown != null) onDown(gameObject); } public void OnPointerEnter(PointerEventData eventData) { if (onEnter != null) onEnter(gameObject); } public void OnPointerExit(PointerEventData eventData) { if (onExit != null) onExit(gameObject); } public void OnSelect(BaseEventData eventData) { if (onSelect != null) onSelect(gameObject); } public void OnUpdateSelected(BaseEventData eventData) { if (onUpdateSelect != null) onUpdateSelect(gameObject); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class ButtonTest : MonoBehaviour { public GameObject btn_Test; void Start() { UIEventListener.Get(btn_Test).onClick = MyButtonEvent; } public void MyButtonEvent(GameObject button) { print("Test"); } }