123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- using SC.XR.Unity;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class EventManager : SingletonMono<EventManager>
- {
- private Dictionary<EventID, List<EventObserver>> m_ObserList = new Dictionary<EventID, List<EventObserver>>();
- 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<EventObserver> 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);
- }
- /// <summary>
- /// 添加监听者
- /// </summary>
- /// <param name="newobj">监听者</param>
- /// <param name="eid">监听的事件</param>
- private void RegisterObj(EventObserver newobj, EventID eid)
- {
- if (!m_ObserList.ContainsKey(eid))
- {
- List<EventObserver> list = new List<EventObserver>();
- list.Add(newobj);
- m_ObserList.Add(eid, list);
- }
- else
- {
- List<EventObserver> list = m_ObserList[eid];
- foreach (EventObserver obj in list)
- {
- if (obj == newobj)
- {
- return;
- }
- }
- list.Add(newobj);
- }
- }
- /// <summary>
- /// 移除监听者
- /// </summary>
- /// <param name="removeobj">监听者</param>
- private void RemoveObj(EventObserver removeobj)
- {
- foreach (KeyValuePair<EventID, List<EventObserver>> kv in m_ObserList)
- {
- List<EventObserver> list = kv.Value;
- foreach (EventObserver obj in list)
- {
- if (obj == removeobj)
- {
- list.Remove(obj);
- break;
- }
- }
- }
- }
- /// <summary>
- /// 移除一个监听者
- /// </summary>
- /// <param name="removeobj">监听者</param>
- public void Remove(EventObserver removeobj)
- {
- if (EventManager.Instance == null) return;
- EventManager.Instance.RemoveObj(removeobj);
- }
- /// <summary>
- /// 监听者在这里注册
- /// </summary>
- /// <param name="newobj">监听者</param>
- /// <param name="eids">需要监听的事件列表.</param>
- 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
- {
- /// <summary>
- /// 选中素材时触发事件
- /// </summary>
- EVENT_1 = 10001,
- EVENT_2 = 10002,
- /// <summary>
- /// 选中锚点
- /// </summary>
- EVENT_3 = 10003,
- }
- public interface EventObserver
- {
- void HandleEvent(EventData resp);
- }
|