在進行Unity相關開發過程中我們總是需要響應很多的事件,如果沒有一個集中的管理,代碼就會變得很混亂,這時候EventManager就變的很重要了。
這裏根據Unity的官方教程:Events: Creating a simple messaging system,通過調用Unity的時間系統來進行封裝。(留下備用)
這裏是Unity官方教程的實現方式,這裏改成了單例模式。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EventManager
{
private Dictionary<string, UnityEvent> eventDictionary = new Dictionary<string, UnityEvent>();
private static EventManager eventManager = new EventManager();
private EventManager()
{
}
public static EventManager GetInstance
{
get
{
return eventManager;
}
}
public void StartListening(string eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.AddListener(listener);
}
else
{
thisEvent = new UnityEvent();
thisEvent.AddListener(listener);
eventManager.eventDictionary.Add(eventName, thisEvent);
}
}
public void StopListening(string eventName, UnityAction listener)
{
if (eventManager == null) return;
UnityEvent thisEvent = null;
if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.RemoveListener(listener);
}
}
public void TriggerEvent(string eventName)
{
UnityEvent thisEvent = null;
if (eventManager.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.Invoke();
}
}
}
事件註冊:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
enum EventEnum
{
start,
Active,
end,
unregistered
}
public class EventTest : MonoBehaviour
{
void Start()
{
EventManager.GetInstance.TriggerEvent(EventEnum.start.ToString());
}
private void OnEnable()
{
EventManager.GetInstance.StartListening(EventEnum.start.ToString(), StartGame);
EventManager.GetInstance.StartListening(EventEnum.Active.ToString(), ActiveGame);
EventManager.GetInstance.StartListening(EventEnum.end.ToString(), EndGame);
}
public void OnDisable()
{
EventManager.GetInstance.StopListening(EventEnum.start.ToString(), StartGame);
EventManager.GetInstance.StopListening(EventEnum.Active.ToString(), ActiveGame);
EventManager.GetInstance.StopListening(EventEnum.end.ToString(), EndGame);
}
public void StartGame()
{
Debug.Log("----------->>>>StartGame");
}
public void ActiveGame()
{
Debug.Log("----------->>>>ActiveGame");
}
public void EndGame()
{
Debug.Log("----------->>>>EndGame");
}
}
事件觸發:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventTrigger : MonoBehaviour
{
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
EventManager.GetInstance.TriggerEvent(EventEnum.Active.ToString());
}
if (Input.GetKeyDown(KeyCode.S))
{
EventManager.GetInstance.TriggerEvent(EventEnum.end.ToString());
}
if (Input.GetKeyDown(KeyCode.D))
{
EventManager.GetInstance.TriggerEvent(EventEnum.start.ToString());
}
if (Input.GetKeyDown(KeyCode.W))
{
EventManager.GetInstance.TriggerEvent(EventEnum.unregistered.ToString());
}
}
}
注:在事件觸發這裏,我觸發了一個沒有被監聽的事件,既沒有相應也沒有錯誤,開發時需要注意。