这里为了满足将整个界面的点击事件整合到一起(一个函数内),这样可以方便的管理维护整个界面的点击事件。
大致使用EventTrigger解决方案。
1、先创建一个脚本,内容如下
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
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;
static public 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);
}
}
使用委托,将按钮点击事件都做一下处理,注意Get()方法,这里将这个脚本给挂在按钮 的物体上面。
2、然后开始在界面类中获取资源的引用,写点击事件。如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickTest : MonoBehaviour, IPointerClickHandler
{
Button btn1;
Button btn2;
// Use this for initialization
void Start ()
{
btn1 = transform.Find("Button").GetComponent<Button>();
btn2 = transform.Find("Button2").GetComponent<Button>();
//EventTriggerListener.Get(btn1.gameObject).onClick = OnButtonClick;
//EventTriggerListener.Get(btn2.gameObject).onClick = OnButtonClick;
Button[] btns = transform.GetComponentsInChildren<Button>();
for(int i=0;i<btns.Length;i++)
{
EventTriggerListener.Get(btns[i].gameObject).onClick = OnButtonClick;
}
}
//单个按钮的回调
private void OnButtonClick(GameObject go)
{
//在这里监听按钮的点击事件
if (go == btn1.gameObject)
{
Debug.Log("btn1");
}
else if (go == btn2.gameObject)
{
Debug.Log("btn2");
}
}
}
以上的例子,就是两个按钮的点击,恩,大致方案如下。第一次写,格式都没弄明白,这里就当自己记录好了。