事件機制廣泛應用于mvc模式中,靈活的事件機制能夠彌補Unity中的一些缺陷,比如協(xié)程的執(zhí)行。因為協(xié)程不能返回值,也不能通過out或者ref傳遞。通過事件機制,可以知道協(xié)程執(zhí)行進度并且返回執(zhí)行結果。當然,這只是個舉例,也只是我習慣用的一種方式。如果有更好的實現(xiàn)方式,希望不吝賜教。
所有要接受事件的腳本,都要繼承這個事件手柄的接口
- /// <summary>
- /// 事件手柄
- /// </summary>
- public interface IEventHandler {
-
- void OnEvent(string type,object data);
- }
以下是EventManager的主要內容,實現(xiàn)了注冊監(jiān)聽,移除監(jiān)聽,派發(fā)事件等基本方法。只要在事件派發(fā)前,注冊好就可以運行了!
- using UnityEngine;
- using System.Collections.Generic;
-
- public class EventManager {
-
- private static EventManager instance;
-
- private Dictionary<string, List<IEventHandler>> dicHandler;
-
- private EventManager()
- {
- dicHandler = new Dictionary<string, List<IEventHandler>>();
- }
-
- public static EventManager GetInstance()
- {
- if (instance == null)
- {
- instance = new EventManager();
- }
- return instance;
- }
-
- /// <summary>
- /// 注冊事件監(jiān)聽
- /// </summary>
- /// <param name="type">監(jiān)聽類型</param>
- /// <param name="listher">監(jiān)聽對象</param>
- public void AddEventListener(string type, IEventHandler listher)
- {
- if (!dicHandler.ContainsKey(type))
- {
- dicHandler.Add(type,new List<IEventHandler>());
- }
- dicHandler[type].Add(listher);
- }
-
- /// <summary>
- /// 移除對type的所有監(jiān)聽
- /// </summary>
- /// <param name="type"></param>
- public void RemoveEventListener(string type)
- {
- if (dicHandler.ContainsKey(type))
- {
- dicHandler.Remove(type);
- }
- }
-
- /// <summary>
- /// 移除監(jiān)聽者的所有監(jiān)聽
- /// </summary>
- /// <param name="listener">監(jiān)聽者</param>
- public void RemoveEventListener(IEventHandler listener)
- {
- foreach (var item in dicHandler)
- {
- if (item.Value.Contains(listener))
- {
- item.Value.Remove(listener);
- }
- }
- }
-
- /// <summary>
- /// 清空所有監(jiān)聽事件
- /// </summary>
- public void ClearEventListener()
- {
- Debug.Log("清空對所有所有所有事件的監(jiān)聽");
- if (dicHandler!=null)
- {
- dicHandler.Clear();
- }
- }
-
- /// <summary>
- /// 派發(fā)事件
- /// </summary>
- /// <param name="type">事件類型</param>
- /// <param name="data">事件傳達的數(shù)據</param>
- public void DispachEvent(string type, object data)
- {
- if (!dicHandler.ContainsKey(type))
- {
- Debug.Log("Did not add any IEventHandler of " + type + " in EventManager!");
- return;
- }
-
- List<IEventHandler> list = dicHandler[type];
- for (int i = 0; i < list.Count; i++)
- {
- list[i].OnEvent(type,data);
- }
- }
- }
本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請
點擊舉報。