按鈕事件監聽NGUI一般常用的是UIEvenetListener,使用方法一般如下
在Lua代碼中使用方式也差不多
對于消息分發,Lua裡面有一個Event實作了類似的功能,但是我們的需求不隻是lua内部分發,還涉及到其他未改成lua的腳本,是以我們使用自己遊戲架構内的消息機制, 基礎原理可以參看以前的文章
那麼在Lua中使用,該怎麼使用,這裡需要進行一些修改。
定義一個字典,存儲目前的lua回調
static public Dictionary<int, List<LuaFunction>> luaEventTable = new Dictionary<int, List<LuaFunction>>();
然後再寫一份對于lua調用的消息機制
static public void LuaAddListener(int eventType, LuaFunction lf)
{
if (luaEventTable.ContainsKey(eventType))
{
luaEventTable[eventType].Add(lf);
}
else
{
List<LuaFunction> list = new List<LuaFunction>();
list.Add(LuaFunction);
luaEventTable.Add(eventType, list);
}
}
static public void LuaRemoveListener(int eventType, LuaFunction lf)
{
if (luaEventTable.ContainsKey(eventType))
{
if (luaEventTable[eventType].Contains(lf))
{
luaEventTable[eventType].Remove(lf);
}
}
}
static public void LuaBroadcast(int eventType, params object[] obj)
{
Broadcast2Lua(eventType, obj);
Delegate d;
if (eventTable.TryGetValue(eventType, out d))
{
d.DynamicInvoke(obj);
}
}
static private void Broadcast2Lua(int eventType, params object[] obj)
{
List<LuaFunction > list = null;
if (luaEventTable.TryGetValue(eventType, out list))
{
for (int j = ; j < list.Count; j++)
{
list[j].Call(obj);
}
}
}
這裡主要的代碼是lua發過來的資訊,有多個參數,而c#裡面的消息資料做了泛型限制,檢視API代碼發現了這個函數,正好滿足我們的需求。
寫好後将此類wrap給lua使用,lua中調用代碼如下
Messege.LuaAddListener(MessageID.LuaTest, this.Test);
Messege.LuaRemoveListener(MessageID.LuaTest, this.Test);
Messege.LuaBroadcast(MessageID.LuaTest, arg1,arg2,arg3);