我们可以像UIEventListener中的Get方法那样动态的添加事件到GameObject上,但是,有比他更好的通用的方式。而且我还可以将其通用于UIEventListener类中。我们看以下代码:
using System;
using System.Collections;
using System.Collections.Generic;
using Object = UnityEngine.Object;//使用特定命名空间类的别名
public class Listener
{
#region 为一个Object添加UIMonoEventListener并返回其实例
public static UIMonoEventListener AddUIMonoEvent(Object o)
{
if(o == null)
{
return null;
}
if(o.GetType() == typeof(Transform))//如果此对象的类型为Transform
{
monoEvent = (o as Transform).GetComponent<UIMonoEventListener>();
}
if(o.GetType() == typeof(GameObject))
{
monoEvent = (o as GameObject).GetComponent<UIMonoEventListener>();
}
if(o.GetType().IsSubclassOf(typeof(MonoBehaviour)))
{
monoEvent = (o as MonoBehaviour).gameObject.GetComponent<UIMonoEventListener>();
}
return monoEvent;
}
#endregion
}
这样一来,我们就可以对一个名为A的GameObject添加Mono事件了,比如:
Listener. AddUIMonoEvent( A ).UpdateMono += __onUpdate;然后我们可以写一个__OnUpdate的毁掉函数来处理OnUpdate事件,很显然,此回调函数也是每帧执行一次的。好了,我们可以试验一下了,新建一个场景,里面只有两个Cube与一个主摄像机,然后新建一个测试脚本:TestMonoEvent,将其绑定在主摄像机上:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public class TestMonoEvent : MonoBehaviour {
public List<GameObject> cubes;
// Use this for initialization
void Start () {
UnityEngine.Object[] gas = FindObjectsOfType(typeof(BoxCollider));//找到带有BoxCollider的这些个类
if(gas == null)
{
return;
}
if(gas.Length == 0)
{
return;
}
foreach (UnityEngine.Object ob in gas)
{
GameObject go = ob as GameObject;
cubes.Add(go);
}
foreach (GameObject go in cubes)
{
if (go.name == "Cube1")
{
Listener.AddUIMonoEvent(go).UpdateMono += new MonoEvent(TestMonoEvent_UpdateMono);
}
else
{
Listener.AddUIMonoEvent(go).StartMono += new MonoEvent(TestMonoEvent_StartMono);
}
}
}
void TestMonoEvent_StartMono()
{
Debug.Log("Start is invoke!");
}
void TestMonoEvent_UpdateMono()
{
Debug.Log("Update is invoke!");
}