YooAsset学习笔记系列
什么是YooAsset:https://github.com/tuyoogame/YooAsset/tree/main 事件管理器EventManager
前言
1.消息包装类PostWrapper
用来封装消息的类,主要用于延迟分发消息
private class PostWrapper
{
public int PostFrame;
public int EventID;
public IEventMessage Message;
public void OnRelease()
{
PostFrame = 0;
EventID = 0;
Message = null;
}
}
2.事件容器
使用字典保存所有已经注册监听的事件 使用 List 数组保存延迟执行的事件
private static readonly Dictionary<int, List<Action<IEventMessage>>> _listeners = new Dictionary<int, List<Action<IEventMessage>>>(1000);
private static readonly List<PostWrapper> _postWrappers = new List<PostWrapper>(1000);
3.注册和移除事件监听
public static void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
{
AddListener(typeof(TEvent), listener);
}
public static void AddListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
AddListener(eventId, listener);
}
public static void AddListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId) == false)
_listeners.Add(eventId, new List<Action<IEventMessage>>());
if (_listeners[eventId].Contains(listener) == false)
_listeners[eventId].Add(listener);
}
public static void RemoveListener(System.Type eventType, System.Action<IEventMessage> listener)
{
int eventId = eventType.GetHashCode();
RemoveListener(eventId, listener);
}
public static void RemoveListener(int eventId, System.Action<IEventMessage> listener)
{
if (_listeners.ContainsKey(eventId))
{
if (_listeners[eventId].Contains(listener))
_listeners[eventId].Remove(listener);
}
}
4.事件分发
实时分发
在当前帧实时广播
public static void SendMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
SendMessage(eventId, message);
}
public static void SendMessage(int eventId, IEventMessage message)
{
if (_listeners.ContainsKey(eventId) == false)
return;
List<Action<IEventMessage>> listeners = _listeners[eventId];
for (int i = listeners.Count - 1; i >= 0; i--)
{
listeners[i].Invoke(message);
}
}
延迟一帧分发
将消息加入延迟数组,等待下一帧分发
public static void PostMessage(IEventMessage message)
{
int eventId = message.GetType().GetHashCode();
PostMessage(eventId, message);
}
public static void PostMessage(int eventId, IEventMessage message)
{
var wrapper = new PostWrapper();
wrapper.PostFrame = UnityEngine.Time.frameCount;
wrapper.EventID = eventId;
wrapper.Message = message;
_postWrappers.Add(wrapper);
}
Update 每帧遍历延迟数组,如果数组中有消息且当前帧大于分发帧则立即分发
public static void Update()
{
for (int i = _postWrappers.Count - 1; i >= 0; i--)
{
var wrapper = _postWrappers[i];
if (UnityEngine.Time.frameCount > wrapper.PostFrame)
{
SendMessage(wrapper.EventID, wrapper.Message);
_postWrappers.RemoveAt(i);
}
}
}
5.移除所有监听
public static void ClearListeners()
{
foreach (int eventId in _listeners.Keys)
{
_listeners[eventId].Clear();
}
_listeners.Clear();
}
|