监听泛型
public class PEListener : MonoBehaviour,IPointerClickHandler,IPointerDownHandler,IPointerUpHandler,IDragHandler{
public Action<object> onClick;
public Action<PointerEventData> onClickDown;
public object args;
public void OnPointerClick(PointerEventData eventData)
{
if (onClick != null)
{
onClick(args);
}
}
public void OnPointerDown(PointerEventData eventData)
{
if (onClickDown != null)
{
onClickDown(eventData);
}
}
}
监听事件
protected T GetOrAddComponent<T>(GameObject go) where T:Component {
T t = go.GetComponent<T>();
if (t == null)
t = go.AddComponent<T>();
return t;
}
protected void OnClick(GameObject go, Action<object> cb,object args)
{
PEListener listener = GetOrAddComponent<PEListener>(go);
listener.onClick = cb;
listener.args = args;
}
protected void OnClickDown(GameObject go, Action<PointerEventData> cb) {
PEListener listener = GetOrAddComponent<PEListener>(go);
listener.onClickDown = cb;
}
多个img添加事件
for (int i = 0; i < posBtnTrans.childCount; i++) {
Image img = posBtnTrans.GetChild(i).GetComponent<Image>();
OnClick(img.gameObject, (object args) =>
{
ClickPosItem((int)args);
audioSvc.PlayUIAudio(Constans.UIClickBtn);
},i);
}
原文:https://www.cnblogs.com/tqvdong/p/14860984.html