Unity中使用EventManager消息管理类处理各种事件
发表于2018-05-18
使用Unity进行开发,肯定会需要去响应各种事件,有些情况下一个事件的触发需要同时进行几项处理。举例让大家可以了解的更清楚:假如有这样一个需求:在点击模型后播放特定模型动画,同时在伴随着播放一段音乐,如果之前有其它音乐正在播放,此时应该立即停止。这种情况下,就可以使用EventManager消息管理类处理各种事件了。
代码如下:
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
public class EventManager : MonoBehaviour {
//这个dic用来管理需要监听的各类事件
private Dictionary <string, UnityEvent> eventDictionary;
private static EventManager eventManager;
//单例
public static EventManager instance
{
get
{
if (!eventManager)
{
//在Unity的Hierarchy中必须有一个名为EventManager的空物体,并挂上EventManager脚本
eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
}
else
{
eventManager.Init ();
}
}
return eventManager;
}
}
void Init ()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<string, UnityEvent>();
}
}
//在需要监听某个事件的脚本中,调用这个方法来监听这个事件
public static void StartListening (string eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.AddListener (listener);
}
else
{
thisEvent = new UnityEvent ();
thisEvent.AddListener (listener);
instance.eventDictionary.Add (eventName, thisEvent);
}
}
//在不需要监听的时候停止监听
public static void StopListening (string eventName, UnityAction listener)
{
if (eventManager == null) return;
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.RemoveListener (listener);
}
}
//触发某个事件
public static void TriggerEvent (string eventName)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.Invoke ();
}
}
}
代码讲解:
场景中添加好这个脚本后,在需要监听某个事件的脚本中这行代码来开始监听某个事件:
EventManager.StartListening ("(事件key值)", listener);
结束监听某个事件:
EventManager.StopListening ("(事件key值)", listener);
某个时刻触发这个事件:
//这里触发了事件之后,上面的listener绑定的事件将会随之触发,如果有多个脚本监听这个事件,也会同时触发这些listenerEventManager.TriggerEvent ("(事件key值)");
