【Unity遊戲開發】用C#和Lua實現Unity中的事件分發機制EventDispatcher

1、簡介

  最近馬三換了一家大公司工做,公司制度規範了一些,所以平時的業餘時間多了很多。可是人卻懶了下來,最近這一個月都沒怎麼研究新技術,博客寫得也是拖拖拉拉,週六周天就躺屍在家看帖子、看小說,要麼就是吃雞,唉!真是罪過罪過。但願能從這篇博客開始有些改善吧,儘可能少玩耍,仍是多學習吧~html

  好了扯得有點遠了,來講說咱們今天博客的主題——「用C#和Lua實現Unity中的事件分發機制」,事件分發機制或者叫事件監聽派發系統,在每一個遊戲框架中都是不可或缺的一個模塊。咱們能夠用它來解耦,監聽網絡消息,或者作一些異步的操做,好處多多(實際上是別人的框架都有這個,因此咱們的框架也必須有這玩意~)。今天馬三就和你們一塊兒,分別使用C#和Lua實現兩種能夠用在Unity遊戲開發中的事件分發處理機制,但願能對你們有些幫助吧~git

2、C#版的事件分發機制

  首先咱們來實現C#版本的事件分發機制,目前這套流程已經集成到了馬三本身的 ColaFrameWork框架 中了。這套框架還在架構階段,裏面不少東西都不完善,馬三也是會隨時把本身的一些想法放到裏面,你們感興趣的話也能夠幫忙維護一下哈!github

  通常來講事件訂閱、派發這種機制都是使用觀察者模式來實現的,本篇博客也不例外,正是利用了這種思想。爲了解耦和麪向接口編程,咱們制定了一個接口IEventHandler,凡是觀察者都須要實現這個接口,而GameEventMgr事件中心維護了一個IEventHandler列表,保存着一系列的觀察者,並在須要的時候進行一系列的動做。這樣操做正是遵循了依賴倒置的設計原則:「高層模塊不該該依賴於低層模塊,二者都應該依賴於抽象概念;」、「抽象接口不該該依賴於實現,而實現應該依賴於抽象接口」。下面的代碼定義了IEventHandler接口和一些委託還有事件傳遞時須要攜帶的參數。編程

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using EventType = ColaFrame.EventType;
 4 
 5 /// <summary>
 6 /// 接收消息後觸發的回調
 7 /// </summary>
 8 /// <param name="data"></param>
 9 public delegate void MsgHandler(EventData data);
10 
11 /// <summary>
12 /// 事件處理器的接口
13 /// </summary>
14 public interface IEventHandler
15 {
16     bool HandleMessage(GameEvent evt);
17 
18     bool IsHasHandler(GameEvent evt);
19 }
20 
21 /// <summary>
22 /// 事件消息傳遞的數據
23 /// </summary>
24 public class EventData
25 {
26     public string Cmd;
27     public List<object> ParaList;
28 }
29 
30 /// <summary>
31 /// 遊戲中的事件
32 /// </summary>
33 public class GameEvent
34 {
35     /// <summary>
36     /// 事件類型
37     /// </summary>
38     public EventType EventType { get; set; }
39     /// <summary>
40     /// 攜帶參數
41     /// </summary>
42     public object Para { get; set; }
43 }
44 
45 
46 namespace ColaFrame
47 {
48     /// <summary>
49     /// 事件的類型
50     /// </summary>
51     public enum EventType : byte
52     {
53         /// <summary>
54         /// 系統的消息
55         /// </summary>
56         SystemMsg = 0,
57         /// <summary>
58         /// 來自服務器推送的消息
59         /// </summary>
60         ServerMsg = 1,
61         /// <summary>
62         /// UI界面消息
63         /// </summary>
64         UIMsg = 2,
65     }
66 }
View Code

  而後咱們再來看一下最核心的事件中心處理器GameEventMgr是如何實現的,仍是先上一下所有的代碼 GameEventMgr.cs:數組

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using UnityEngine;
  5 using EventType = ColaFrame.EventType;
  6 
  7 /// <summary>
  8 /// 事件消息管理中心
  9 /// </summary>
 10 public class GameEventMgr
 11 {
 12     /// <summary>
 13     /// 存儲Hander的字典
 14     /// </summary>
 15     private Dictionary<int, List<IEventHandler>> handlerDic;
 16 
 17     private static GameEventMgr instance = null;
 18 
 19     private GameEventMgr()
 20     {
 21         handlerDic = new Dictionary<int, List<IEventHandler>>();
 22     }
 23 
 24     public static GameEventMgr GetInstance()
 25     {
 26         if (null == instance)
 27         {
 28             instance = new GameEventMgr();
 29         }
 30         return instance;
 31     }
 32 
 33     /// <summary>
 34     /// 對外提供的註冊監聽的接口
 35     /// </summary>
 36     /// <param name="handler"></param>監聽者(處理回調)
 37     /// <param name="eventTypes"></param>想要監聽的事件類型
 38     public void RegisterHandler(IEventHandler handler, params EventType[] eventTypes)
 39     {
 40         for (int i = 0; i < eventTypes.Length; i++)
 41         {
 42             RegisterHandler(eventTypes[i], handler);
 43         }
 44     }
 45 
 46     /// <summary>
 47     /// 內部實際調用的註冊監聽的方法
 48     /// </summary>
 49     /// <param name="type"></param>要監聽的事件類型
 50     /// <param name="handler"></param>監聽者(處理回調)
 51     private void RegisterHandler(EventType type, IEventHandler handler)
 52     {
 53         if (null != handler)
 54         {
 55             if (!handlerDic.ContainsKey((int)type))
 56             {
 57                 handlerDic.Add((int)type, new List<IEventHandler>());
 58             }
 59             if (!handlerDic[(int)type].Contains(handler))
 60             {
 61                 handlerDic[(int)type].Add(handler);
 62             }
 63         }
 64     }
 65 
 66     /// <summary>
 67     /// 反註冊事件監聽的接口,對全部類型的事件移除指定的監聽
 68     /// </summary>
 69     /// <param name="handler"></param>
 70     public void UnRegisterHandler(IEventHandler handler)
 71     {
 72         using (var enumerator = handlerDic.GetEnumerator())
 73         {
 74             List<IEventHandler> list;
 75             while (enumerator.MoveNext())
 76             {
 77                 list = enumerator.Current.Value;
 78                 list.Remove(handler);
 79             }
 80         }
 81     }
 82 
 83     /// <summary>
 84     /// 反註冊事件監聽的接口,移除指定類型事件的監聽
 85     /// </summary>
 86     /// <param name="handler"></param>
 87     /// <param name="types"></param>
 88     public void UnRegisterHandler(IEventHandler handler, params EventType[] types)
 89     {
 90         EventType type;
 91         for (int i = 0; i < types.Length; i++)
 92         {
 93             type = types[i];
 94             if (handlerDic.ContainsKey((int)type) && handlerDic[(int)type].Contains(handler))
 95             {
 96                 handlerDic[(int)type].Remove(handler);
 97             }
 98         }
 99     }
100 
101     /// <summary>
102     /// 分發事件
103     /// </summary>
104     /// <param name="gameEvent"></param>想要分發的事件
105     public void DispatchEvent(GameEvent gameEvent)
106     {
107         bool eventHandle = false;
108 
109         List<IEventHandler> handlers;
110         if (null != gameEvent && handlerDic.TryGetValue((int)gameEvent.EventType, out handlers))
111         {
112             for (int i = 0; i < handlers.Count; i++)
113             {
114                 try
115                 {
116                     eventHandle = handlers[i].HandleMessage(gameEvent) || eventHandle;
117                 }
118                 catch (Exception e)
119                 {
120                     Debug.LogError(e);
121                 }
122             }
123 
124             if (!eventHandle)
125             {
126                 if (null != gameEvent)
127                 {
128                     switch (gameEvent.EventType)
129                     {
130                         case EventType.ServerMsg:
131                             break;
132                         default:
133                             Debug.LogError("消息未處理,類型:" + gameEvent.EventType);
134                             break;
135                     }
136                 }
137             }
138         }
139     }
140 
141     /// <summary>
142     /// 分發事件
143     /// </summary>
144     /// <param name="evt"></param>分發的消息名稱
145     /// <param name="eventType"></param>消息事件類型
146     /// <param name="para"></param>參數
147     public void DispatchEvent(string evt, EventType eventType = EventType.UIMsg, params object[] para)
148     {
149         GameEvent gameEvent = new GameEvent();
150         gameEvent.EventType = eventType;
151         EventData eventData = new EventData();
152         eventData.Cmd = evt;
153         if (null != para)
154         {
155             eventData.ParaList = new List<object>();
156             for (int i = 0; i < para.Length; i++)
157             {
158                 eventData.ParaList.Add(para[i]);
159             }
160         }
161         gameEvent.Para = eventData;
162 
163         this.DispatchEvent(gameEvent);
164     }
165 
166     /// <summary>
167     /// 分發事件
168     /// </summary>
169     /// <param name="evt"></param>分發的消息名稱
170     /// <param name="eventType"></param>消息事件類型
171     public void DispatchEvent(string evt, EventType eventType = EventType.UIMsg)
172     {
173         GameEvent gameEvent = new GameEvent();
174         gameEvent.EventType = eventType;
175         EventData eventData = new EventData();
176         eventData.Cmd = evt;
177         eventData.ParaList = null;
178         gameEvent.Para = eventData;
179 
180         this.DispatchEvent(gameEvent);
181     }
182 }
View Code

咱們在其內部維護了一個handlerDic字典,它的key是int類型的,對應的其實就是咱們在上面定義的EventType 這個枚舉,它的value是一個元素爲IEventHandler類型的列表,也就是說咱們按照不一樣的事件類型,將監聽者分爲了幾類進行處理。監聽者是能夠監聽多個消息類型的,也就是說一個監聽者實例能夠存在於多個列表中,這樣並不會產生衝突。咱們就從RegisterHandler(IEventHandler handler, params EventType[] eventType)這個對外提供的註冊監聽的接口入手,逐步的分析一下它的工做流程:服務器

  1. 調用RegisterHandler方法,傳入監聽者和須要監聽的事件類型(能夠是數組,支持多個事件類型),而後遍歷事件類型,依次調用RegisterHandler(EventType type, IEventHandler handler)接口,將監聽者逐個的註冊到每一個事件類型對應的監聽者列表中;
  2. 當須要分發事件的時候,調用DispatchEvent方法,傳入一個GameEvent類型的參數gameEvent,它包含了須要派發的事件屬於什麼類型,和對應的事件消息須要傳遞的參數,其中這個參數又包含了字符串具體的事件名稱和一個參數列表;
  3. 在DispatchEvent中,會根據事件類型來判斷內部字段中是否有註冊了該事件的監聽者,若是有就取到存有這個監聽者的列表;
  4. 而後依次遍歷每一個監聽者,調用其HandleMessage方法,進行具體消息的處理,該函數還會返回一個bool值,表示是否處理了該消息。若是遍歷了全部的監聽者之後,發現沒有處理該消息的監聽者,則會打印一個錯誤消息進行提示;
  5. DispatchEvent(string evt, EventType eventType = EventType.UIMsg, params object[] para)和DispatchEvent(string evt, EventType eventType = EventType.UIMsg)這兩個接口是對DispatchEvent接口的進一步封裝,方便用戶進行無參消息派發和含參數消息派發;

最後咱們再來看一下具體的監聽者應該如何實現IEventHandler接口,以 ColaFrameWork框架 中的UI基類——UIBase舉例,在UIBase內部維護了一個Dictionary<string, MsgHandler> msgHanderDic 結構,用它來保存具體的事件名稱對應的回調函數,而後再去具體地實現HandleMessage和IsHasHandler接口中的抽象方法,代碼以下:微信

 1 /// <summary>
 2     /// 處理消息的函數的實現
 3     /// </summary>
 4     /// <param name="gameEvent"></param>事件
 5     /// <returns></returns>是否處理成功
 6     public bool HandleMessage(GameEvent evt)
 7     {
 8         bool handled = false;
 9         if (EventType.UIMsg == evt.EventType)
10         {
11             if (null != msgHanderDic)
12             {
13                 EventData eventData = evt.Para as EventData;
14                 if (null != eventData && msgHanderDic.ContainsKey(eventData.Cmd))
15                 {
16                     msgHanderDic[eventData.Cmd](eventData);
17                     handled = true;
18                 }
19             }
20         }
21         return handled;
22     }
23 
24     /// <summary>
25     /// 是否處理了該消息的函數的實現
26     /// </summary>
27     /// <returns></returns>是否處理
28     public bool IsHasHandler(GameEvent evt)
29     {
30         bool handled = false;
31         if (EventType.UIMsg == evt.EventType)
32         {
33             if (null != msgHanderDic)
34             {
35                 EventData eventData = evt.Para as EventData;
36                 if (null != eventData && msgHanderDic.ContainsKey(eventData.Cmd))
37                 {
38                     handled = true;
39                 }
40             }
41         }
42         return handled;
43     }

爲了使用更加簡潔方便,咱們還能夠再封裝一些函數出來,以便隨時註冊一個消息和取消註冊一個消息,主要是RegisterEvent和UnRegisterEvent接口,代碼以下:網絡

 1 /// <summary>
 2     /// 初始化註冊消息監聽
 3     /// </summary>
 4     protected void InitRegisterHandler()
 5     {
 6         msgHanderDic = null;
 7         GameEventMgr.GetInstance().RegisterHandler(this, EventType.UIMsg);
 8         msgHanderDic = new Dictionary<string, MsgHandler>()
 9         {
10         };
11     }
12 
13     /// <summary>
14     /// 取消註冊該UI監聽的全部消息
15     /// </summary>
16     protected void UnRegisterHandler()
17     {
18         GameEventMgr.GetInstance().UnRegisterHandler(this);
19 
20         if (null != msgHanderDic)
21         {
22             msgHanderDic.Clear();
23             msgHanderDic = null;
24         }
25     }
26 
27     /// <summary>
28     /// 註冊一個UI界面上的消息
29     /// </summary>
30     /// <param name="evt"></param>
31     /// <param name="msgHandler"></param>
32     public void RegisterEvent(string evt, MsgHandler msgHandler)
33     {
34         if (null != msgHandler && null != msgHanderDic)
35         {
36             if (!msgHanderDic.ContainsKey(evt))
37             {
38                 msgHanderDic.Add(Name + evt, msgHandler);
39             }
40             else
41             {
42                 Debug.LogWarning(string.Format("消息{0}重複註冊!", evt));
43             }
44         }
45     }
46 
47     /// <summary>
48     /// 取消註冊一個UI界面上的消息
49     /// </summary>
50     /// <param name="evt"></param>
51     public void UnRegisterEvent(string evt)
52     {
53         if (null != msgHanderDic)
54         {
55             msgHanderDic.Remove(Name + evt);
56         }
57     }

 關於C#版的事件分發機制大概就介紹到這裏了,馬三在這裏只是大概地講了下思路,更細緻的原理和使用方法你們能夠去馬三的 ColaFrameWork框架 中找一下相關代碼。架構

3、Lua版的事件分發機制

  Lua版本的事件分發機制相對C#版的來講就簡單了不少,Lua中沒有接口的概念,所以實現方式和C#版的也大有不一樣,不過總的來講仍是對外暴露出如下幾個接口:框架

  • Instance():獲取單例
  • RegisterEvent():註冊一個事件
  • UnRegisterEvent():反註冊一個事件
  • DispatchEvent():派發事件
  • AddEventListener():增長監聽者
  • RemoveEventListener():移除監聽者

  照例仍是先上一下核心代碼EventMgr.lua,而後再逐步解釋:

 1 require("Class")
 2 local bit = require "bit"
 3 
 4 EventMgr = {
 5     --實例對象
 6     _instance = nil,
 7     --觀察者列表
 8     _listeners = nil
 9 }
10 EventMgr.__index = EventMgr
11 setmetatable(EventMgr, Class)
12 
13 -- 構造器
14 function EventMgr:new()
15     local t = {}
16     t = Class:new()
17     setmetatable(t, EventMgr)
18     return t
19 end
20 
21 -- 獲取單例接口
22 function EventMgr:Instance()
23     if EventMgr._instance == nil then
24         EventMgr._instance = EventMgr:new()
25         EventMgr._listeners = {}
26     end
27     return EventMgr._instance
28 end
29 
30 function EventMgr:RegisterEvent(moduleId, eventId, func)
31     local key = bit.lshift(moduleId, 16) + eventId
32     self:AddEventListener(key, func, nil)
33 end
34 
35 function EventMgr:UnRegisterEvent(moduleId, eventId, func)
36     local key = bit.lshift(moduleId, 16) + eventId
37     self:RemoveEventListener(key, func)
38 end
39 
40 function EventMgr:DispatchEvent(moduleId, eventId, param)
41     local key = bit.lshift(moduleId, 16) + eventId
42     local listeners = self._listeners[key]
43     if nil == listeners then
44         return
45     end
46     for _, v in ipairs(listeners) do
47         if v.p then
48             v.f(v.p, param)
49         else
50             v.f(param)
51         end
52     end
53 end
54 
55 function EventMgr:AddEventListener(eventId, func, param)
56     local listeners = self._listeners[eventId]
57     -- 獲取key對應的監聽者列表,結構爲{func,para},若是沒有就新建
58     if listeners == nil then
59         listeners = {}
60         self._listeners[eventId] = listeners -- 保存監聽者
61     end
62     --過濾掉已經註冊過的消息,防止重複註冊
63     for _, v in pairs(listeners) do
64         if (v and v.f == func) then
65             return
66         end
67     end
68     --if func == nil then
69     --    print("func is nil!")
70     --end
71     --加入監聽者的回調和參數
72     table.insert(listeners, { f = func, p = param })
73 end
74 
75 function EventMgr:RemoveEventListener(eventId, func)
76     local listeners = self._listeners[eventId]
77     if nil == listeners then
78         return
79     end
80     for k, v in pairs(listeners) do
81         if (v and v.f == func) then
82             table.remove(listeners, k)
83             return
84         end
85     end
86 end

  在實際使用的時候主要是調用 RegisterEvent、UnRegisterEvent 和 DispatchEvent這三個接口。RegisterEvent用來註冊一個事件,UnRegisterEvent 用來反註冊一個事件,DispatchEvent用來派發事件。先從RegisterEvent接口提及,它須要傳入3個參數,分別是ModuleId,EventId和回調函數func。ModuleId就是咱們不一樣模塊的id,他是一個模塊的惟一標識,在實際應用中咱們能夠定義一個全局的枚舉來標識這些模塊ID。EventId是不一樣的消息的標識,它也是數字類型的枚舉值,而且由於有了模塊ID的存在,不一樣模塊可使用相同的EventId,這並不會致使消息的衝突。在RegisterEvent內部操做中,咱們首先對ModuleId進行了左移16位的操做,而後再加上EventID組成咱們的消息key,左移16位能夠避免ModuleID直接與EventId組合後會產生Key衝突的問題,通常來講左移16位已經能夠知足定義不少模塊和事件id的需求了。而後調用 self:AddEventListener(key, func, nil) 方法,將計算出來的key和回調函數進行註冊。在EventMgr的內部其實仍是維護了一個監聽者列表,註冊消息的時候,就是把回調和參數添加到監聽者列表中。反註冊消息就是把對應key的回調從監聽者列表中移除。派發事件的時候就是遍歷key所對應的監聽者列表,而後依次執行裏面的回調函數。好了,接着說AddEventListener這個函數的操做,它首先會去獲取key對應的監聽者列表,結構爲{func,para},若是沒有就新建一個table,並把它保存爲key所對應的監聽者列表。獲得這個監聽者列表之後,咱們首先會對其進行遍歷,若是裏面已經包含func回調函數的話,就直接return掉,過濾掉已經註冊過的消息,防止重複註冊。若是經過了上一步檢查的話,就執行 table.insert(listeners, { f = func, p = param })操做,加入監聽者的回調和參數。對於UnRegisterEvent方法,咱們依然會計算出key,而後調用 RemoveEventListener 操做,把監聽者從監聽者列表中移除。在使用DispatchEvent接口進行事件派發的時候,咱們依然會先計算出Key,而後取出key對應的監聽者列表。接着依次遍歷這些監聽者,而後執行其中保存着的回調函數,而且把須要傳遞的事件參數傳遞進去。具體的使用方法,能夠參考下面的Main.lua:

 1 require("EventMgr")
 2 
 3 local function TestCallback_1()
 4     print("Callback_1")
 5 end
 6 
 7 local function TestCallback_2(param)
 8     print("Callback_2")
 9     print(param.id)
10     print(param.pwd)
11 end
12 
13 local EventMgr = EventMgr:Instance()
14 EventMgr:RegisterEvent(1, 1, TestCallback_1)
15 EventMgr:RegisterEvent(2, 1, TestCallback_2)
16 EventMgr:DispatchEvent(1, 1)
17 EventMgr:DispatchEvent(2, 1, { id = "abc", pwd = "123" })

支持含參數事件分發和無參數事件分發,上面代碼的執行結果以下,能夠發現成功地監聽了註冊的消息,而且也獲取到了傳遞過來的參數:

 

 圖1:代碼執行結果

4、總結

經過本篇博客,馬三和你們一塊兒學習瞭如何在Unity中使用C#和Lua分別實現事件分發機制,但願本篇博客能爲你們的工做過程當中帶來一些幫助與啓發。

本篇博客中的樣例工程已經同步至Github:https://github.com/XINCGer/Unity3DTraining/tree/master/lua/LuaEventMgr,歡迎你們Fork! 

馬三的開源Unity客戶端框架 ColaFramework框架:https://github.com/XINCGer/ColaFrameWork

若是以爲本篇博客對您有幫助,能夠掃碼小小地鼓勵下馬三,馬三會寫出更多的好文章,支持微信和支付寶喲!

       

 

 

 

做者:馬三小夥兒
出處:http://www.javashuo.com/article/p-uesjkemq-r.html 
請尊重別人的勞動成果,讓分享成爲一種美德,歡迎轉載。另外,文章在表述和代碼方面若有不妥之處,歡迎批評指正。留下你的腳印,歡迎評論!

 

個人博客即將搬運同步至騰訊雲+社區,邀請你們一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=3s3rkmf0oback

相關文章
相關標籤/搜索