该脚本只适用于UGUI
在Unity中添加监听的方法一般是不含参的。但若是需要传参则AddListener(delegate()=>Func(string str)) 即可。但是今天在Unity中用UGUI的一个Button按钮绑定一个监听的同时要把Button按钮本身当作参数传入方法中对按钮的子物体进行操作。但结果是能获取到Button本身,但是获取不到其身上的组件和子物体的组件。查找其身上的组件时会报错找不到该对象。所以使用一个工具类EventTriggerListener完美解决了这个问题。
使用方法为:
EventTriggerListener.Get(需要绑定监听的Button的gameObject
).onClick = OnCallBack;
其监听要执行的方法即为:
private void OnCallBack(GameObject go)
{}
—————————————————————————————————
脚本代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class EventTriggerListener : UnityEngine.EventSystems.EventTrigger
{
public delegate void VoidDelegate(GameObject go);
public VoidDelegate onClick;
public VoidDelegate onDown;
public VoidDelegate onEnter;
public VoidDelegate onExit;
public VoidDelegate onUp;
public VoidDelegate onSelect;
public VoidDelegate onUpdateSelect;
public static EventTriggerListener Get(GameObject go)
{
EventTriggerListener listener = go.GetComponent<EventTriggerListener>();
if (listener == null) listener = go.AddComponent<EventTriggerListener>();
return listener;
}
public override void OnPointerClick(PointerEventData eventData)
{
if (onClick != null) onClick(gameObject);
}
public override void OnPointerDown(PointerEventData eventData)
{
if (onDown != null) onDown(gameObject);
}
public override void OnPointerEnter(PointerEventData eventData)
{
if (onEnter != null) onEnter(gameObject);
}
public override void OnPointerExit(PointerEventData eventData)
{
if (onExit != null) onExit(gameObject);
}
public override void OnPointerUp(PointerEventData eventData)
{
if (onUp != null) onUp(gameObject);
}
public override void OnSelect(BaseEventData eventData)
{
if (onSelect != null) onSelect(gameObject);
}
public override void OnUpdateSelected(BaseEventData eventData)
{
if (onUpdateSelect != null) onUpdateSelect(gameObject);
}
}