在使用Unity進(jìn)行開(kāi)發(fā)的過(guò)程中,我們總需要響應(yīng)各種事件,有時(shí)一個(gè)事件的觸發(fā)需要我們同時(shí)進(jìn)行幾項(xiàng)處理。舉個(gè)例子:比如我們有這樣的需求:點(diǎn)擊模型之后播放特定模型動(dòng)畫(huà),同時(shí)播放一段音樂(lè),如果之前有其它音樂(lè)正在播放,也應(yīng)該立即停止。在這種情況下,我們就可以使用這個(gè)EventManager類(lèi)來(lái)處理這種需求。
一、寫(xiě)在前面
代碼來(lái)自Unity官方教程:Events: Creating a simple messaging system
在實(shí)際項(xiàng)目開(kāi)發(fā)過(guò)程中,感覺(jué)比較好用,分享給大家。
二、代碼
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
public class EventManager : MonoBehaviour {
//這個(gè)dic用來(lái)管理需要監(jiān)聽(tīng)的各類(lèi)事件
private Dictionary <string, UnityEvent> eventDictionary;
private static EventManager eventManager;
//單例
public static EventManager instance
{
get
{
if (!eventManager)
{
//在Unity的Hierarchy中必須有一個(gè)名為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>();
}
}
//在需要監(jiān)聽(tīng)某個(gè)事件的腳本中,調(diào)用這個(gè)方法來(lái)監(jiān)聽(tīng)這個(gè)事件
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);
}
}
//在不需要監(jiān)聽(tīng)的時(shí)候停止監(jiān)聽(tīng)
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);
}
}
//觸發(fā)某個(gè)事件
public static void TriggerEvent (string eventName)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.Invoke ();
}
}
}
2.1代碼講解
場(chǎng)景中添加好這個(gè)腳本后,在需要監(jiān)聽(tīng)某個(gè)事件的腳本中這行代碼來(lái)開(kāi)始監(jiān)聽(tīng)某個(gè)事件:
EventManager.StartListening ("(事件key值)", listener);
結(jié)束監(jiān)聽(tīng)某個(gè)事件:
EventManager.StopListening ("(事件key值)", listener);
某個(gè)時(shí)刻觸發(fā)這個(gè)事件:
//這里觸發(fā)了事件之后,上面的listener綁定的事件將會(huì)隨之觸發(fā),如果有多個(gè)腳本監(jiān)聽(tīng)這個(gè)事件,也會(huì)同時(shí)觸發(fā)這些listener
EventManager.TriggerEvent ("(事件key值)");
三、工程Demo
對(duì)于想要看整個(gè)工程demo的,可以去上面給出的鏈接中找,我自己也寫(xiě)了個(gè)Demo項(xiàng)目在這里,有需要的可以自行下載。PS:由于博客更新的時(shí),我已經(jīng)把Unity版本升級(jí)到了2017.1.0f3,所以需要下載Unity最新版喲~
https://pan.baidu.com/s/1mhIxWus 密碼:y2uf