using UnityEngine;
using System.Collections.Generic;
namespace FlowCanvas.Framework
{
public delegate void UIMsgCallBack(object[] args);
public class UIMsg
{
public string id;
public object[] args;
public UIMsg() { }
public UIMsg(string id, object[] args)
{
this.id = id;
this.args = args;
}
}
public class UIMsgMgr : MonoBehaviour
{
private static UIMsgMgr _instance = null;
public static UIMsgMgr GetInstance()
{
if (_instance == null)
{
_instance = FindObjectOfType<UIMsgMgr>();
if (_instance == null)
{
_instance = new GameObject("_UIMsgMgr").AddComponent<UIMsgMgr>();
}
}
return _instance;
}
// 消息队列
private Queue<UIMsg> _msgQueue = new Queue<UIMsg>();
// 监听消息
private Dictionary<string, List<UIMsgCallBack>> _msgListener = new Dictionary<string, List<UIMsgCallBack>>();
public void Register(string msgId, UIMsgCallBack cb)
{
if (!_msgListener.ContainsKey(msgId))
{
_msgListener.Add(msgId, new List<UIMsgCallBack>());
_msgListener[msgId].Add(cb);
}
_msgListener[msgId].Add(cb);
}
public void Post(string msgId, object[] msgArgs = null)
{
_msgQueue.Enqueue(new UIMsg(msgId, msgArgs));
}
public void Clear()
{
_msgQueue.Clear();
_msgListener.Clear();
}
public void Update()
{
DispatchAllMsg();
}
private void DispatchAllMsg()
{
// 一次抛出所有的msg
for (int i = 0; i < _msgQueue.Count; i++)
{
UIMsg msg = _msgQueue.Dequeue();
Dispatch(msg);
}
}
private void Dispatch(UIMsg msg)
{
string id = msg.id;
object[] args = msg.args;
if (_msgListener.ContainsKey(id))
{
List<UIMsgCallBack> cbList = _msgListener[id];
for (int i = 0; i < cbList.Count; i++)
{
UIMsgCallBack cb = cbList[i];
cb(args);
}
}
}
}
}
# coding: utf-8
# 消息队列
import traceback
from glog import glog, gout, glogout
from Queue import Queue
from helper import EmptyObject
global G
G = EmptyObject()
G.queue = Queue() # 消息缓存
G.listener = {} # 收听者
# 注册消息
def reg(msg, cb):
global G
if not msg in G.listener:
G.listener[msg] = []
G.listener[msg].append(cb)
# 发送消息
def post(msg, data=None):
global G
# 放入消息队列
G.queue.put((msg, data))
# 发布所有消息队列中的消息
def dispatch_all_message():
global G
q = G.queue
# 取出消息
messages = []
while True:
item = None
try:
item = q.get_nowait()
except Exception, e:
#print(traceback.format_exc())
pass
if item:
messages.append(item)
else:
break
# 循环发布
for msg, data in messages:
_dispatch(msg, data)
def _dispatch(msg, data):
global G
if msg in G.listener:
for cb in G.listener[msg]:
# 调用回调
cb(data)
else:
glogout("[message_queue] this message no listener:", msg)
def update():
# 发布
dispatch_all_message()
# ---------------------------------------
# test
# ---------------------------------------
def test():
def cb(data):
print "cb:", data
reg("test message", cb)
post("test message", "test data")
update() # loop
if __name__ == "__main__":
test()