使用UnityEvent需要引用UnityEngine.Events
官方示例代码:
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
public class Work: MonoBehaviour {
//声明响应事件
UnityEvent m_MyEvent;
void Start() {
if (m_MyEvent == null)
m_MyEvent = new UnityEvent();
//添加监听
m_MyEvent.AddListener(Ping);
m_MyEvent.AddListener(Ping1);
}
void Update() {
if (Input.anyKeyDown && m_MyEvent != null) {
//回调方法,执行监听方法
m_MyEvent.Invoke();
}
}
void Ping() {
Debug.Log("Ping");
}
void Ping1() {
Debug.Log("Ping1");
}
}
调用事件的回调方法Invoke时,会调用添加监听的方法
移除监听使用RemoveListener()或RemoveAllListener()
if (Input.GetKeyDown(KeyCode.R) && m_MyEvent != null) {
//移除Ping1()的监听方法
m_MyEvent.RemoveListener(Ping1);
}
if (Input.GetKeyDown(KeyCode.A) && m_MyEvent != null) {
//移除所有的监听方法
m_MyEvent.RemoveAllListener();
}
*带参数的UnityEvent<>
要调用带参数的事件方法,需要实例化继承UnityEvent<T>接口的类
官方示例代码:
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class MyIntEvent : UnityEvent<int>
{
}
public class ExampleClass : MonoBehaviour{
public MyIntEvent m_MyEvent;
void Start() {
if (m_MyEvent == null)
m_MyEvent = new MyIntEvent();
m_MyEvent.AddListener(Ping);
}
void Update() {
if (Input.anyKeyDown && m_MyEvent != null) {
m_MyEvent.Invoke(5);
}
}
void Ping(int i){
Debug.Log("Ping" + i);
}
}