在游戏开发的基本思想中,逻辑与表现的分离极为重要,相互之间并不关心具体实现,只注册对应的事件,有事件发生时才调用相应的函数
事件管理器
using System.Collections;
using System.Collections.Generic;public class event_manager : Singletom<event_manager> {public delegate void on_event_handler(string name, object udata);private Dictionary<string, on_event_handler> event_listeners = new Dictionary<string,on_event_handler>();// 订阅者而言public void add_event_listener(string name, on_event_handler handler) {if (this.event_listeners.ContainsKey(name)) {this.event_listeners[name] += handler;}else {this.event_listeners.Add(name, handler);}}public void remove_event_listener(string name, on_event_handler handler) {if (!this.event_listeners.ContainsKey(name)) {return;}this.event_listeners[name] -= handler;if (this.event_listeners[name] == null) {this.event_listeners.Remove(name);}}// end // 发布public void dispatch_event(string name, object udata) {if (!this.event_listeners.ContainsKey(name)) {return;}if (this.event_listeners[name] != null) {this.event_listeners[name](name, udata);}}// end }
使用
发布
event_manager.Instance.dispatch_event("coin", (object)100);
订阅
void on_coin_value(string name, object udata) {int coin = (int)udata;Debug.Log("coin = " + coin);
}
event_manager.Instance.add_event_listener("coin", this.on_coin_value);