From 3b036c6de871aa519a1f7fbfb52e09618945041f Mon Sep 17 00:00:00 2001 From: chai <215380520@qq.com> Date: Mon, 15 May 2023 09:28:11 +0800 Subject: *misc --- .../Tools/Notification/ScopedNotification.cs | 89 ++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 WorldlineKeepers/Assets/Scripts/Tools/Notification/ScopedNotification.cs (limited to 'WorldlineKeepers/Assets/Scripts/Tools/Notification/ScopedNotification.cs') diff --git a/WorldlineKeepers/Assets/Scripts/Tools/Notification/ScopedNotification.cs b/WorldlineKeepers/Assets/Scripts/Tools/Notification/ScopedNotification.cs new file mode 100644 index 0000000..0002f14 --- /dev/null +++ b/WorldlineKeepers/Assets/Scripts/Tools/Notification/ScopedNotification.cs @@ -0,0 +1,89 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace WK +{ + + public class ScopedNotification + { + public delegate void NotificatonHandler(params object[] args); + + private Dictionary> m_EventListeners = new Dictionary>(); + + public void AddObserver(string eventName, NotificatonHandler handler) + { + if (handler == null) + { + return; + } + + if (string.IsNullOrEmpty(eventName)) + { + return; + } + + List handlers; + if (!m_EventListeners.ContainsKey(eventName)) + { + m_EventListeners.Add(eventName, new List()); + } + + handlers = m_EventListeners[eventName]; + handlers.Add(handler); + } + + public void RemoveObserver(string eventName, NotificatonHandler handler) + { + if(handler == null) { return; } + + if(string.IsNullOrEmpty(eventName)) { return; } + + if (!m_EventListeners.ContainsKey(eventName)) + return; + + List handlers = m_EventListeners[eventName]; + if(handlers.Contains(handler)) + handlers.Remove(handler); + } + + public void RemoveEvent(string eventName) + { + if (string.IsNullOrEmpty(eventName)) { return; } + if(m_EventListeners.ContainsKey(eventName)) + { + m_EventListeners.Remove(eventName); + } + } + + public void Clean() + { + m_EventListeners.Clear(); + } + + public void PostNotification(string eventName, params object[] args) + { + if (string.IsNullOrEmpty(eventName)) { return; } + + if (!m_EventListeners.ContainsKey(eventName)) + return; + + List handlers = m_EventListeners[eventName]; + for(int i = 0; i < handlers.Count; i++) + { + var handler = handlers[i]; + if(handler != null) + { + handler(args); + } + } + } + + public void PostNotification(string eventName) + { + PostNotification(eventName, null); + } + + } + +} \ No newline at end of file -- cgit v1.1-26-g67d0