using SC.XR.Unity; using System.Collections; using System.Collections.Generic; using UnityEngine; public class EventManager : SingletonMono { private Dictionary> m_ObserList = new Dictionary>(); private Queue m_Quene = new Queue(); private void Update() { while (m_Quene.Count > 0) { EventData data = (EventData)m_Quene.Dequeue(); if (!m_ObserList.ContainsKey(data.ID)) { continue; } List observers = m_ObserList[data.ID]; for (int i = 0; i < observers.Count; i++) { if (observers[i] == null) { continue; } observers[i].HandleEvent(data); } } } //发送事件 public void SendEvent(EventData eve) { m_Quene.Enqueue(eve); } /// /// 添加监听者 /// /// 监听者 /// 监听的事件 private void RegisterObj(EventObserver newobj, EventID eid) { if (!m_ObserList.ContainsKey(eid)) { List list = new List(); list.Add(newobj); m_ObserList.Add(eid, list); } else { List list = m_ObserList[eid]; foreach (EventObserver obj in list) { if (obj == newobj) { return; } } list.Add(newobj); } } /// /// 移除监听者 /// /// 监听者 private void RemoveObj(EventObserver removeobj) { foreach (KeyValuePair> kv in m_ObserList) { List list = kv.Value; foreach (EventObserver obj in list) { if (obj == removeobj) { list.Remove(obj); break; } } } } /// /// 移除一个监听者 /// /// 监听者 public void Remove(EventObserver removeobj) { if (EventManager.Instance == null) return; EventManager.Instance.RemoveObj(removeobj); } /// /// 监听者在这里注册 /// /// 监听者 /// 需要监听的事件列表. public void Register(EventObserver newobj, params EventID[] eids) { if (EventManager.Instance == null) return; foreach (EventID eid in eids) { EventManager.Instance.RegisterObj(newobj, eid); } } private void on() { //m_Quene.Clear(); } private void OnApplicationQuit() { m_ObserList.Clear(); } } public enum EventID { /// /// 选中素材时触发事件 /// EVENT_1 = 10001, EVENT_2 = 10002, /// /// 选中锚点 /// EVENT_3 = 10003, } public interface EventObserver { void HandleEvent(EventData resp); }