using UnityEngine; using System.Collections; using System; //Based off http://forum.unity3d.com/threads/37896-Programming-architectures?p=847646&viewfull=1#post847646 //Changed it to static methods (less typing and less indirection) //Added helper methods for posting notifications public class GenericNotificationCenter where NT : struct, IConvertible, IComparable, IFormattable where N : GenericNotification, new() { public delegate void OnNotificationDelegate(N note); private static OnNotificationDelegate[] _listeners = new OnNotificationDelegate[System.Enum.GetValues(typeof(NT)).Length]; public static void AddListener(OnNotificationDelegate newListenerDelegate, NT type) { int typeInt = type.ToInt32(null); //Note that these checks will only be done when DEBUG is defined _listeners[typeInt] += newListenerDelegate; } static bool IsAlreadyRegistered(OnNotificationDelegate newListenerDelegate, int typeInt) { if (_listeners[typeInt] == null) { return false; } Delegate[] invocationList = _listeners[typeInt].GetInvocationList(); foreach (Delegate d in invocationList) { if (d == newListenerDelegate) { return true; } } return false; } public static void RemoveListener(OnNotificationDelegate listenerDelegate, NT type) { int typeInt = type.ToInt32(null); _listeners[typeInt] -= listenerDelegate; } public static void Post(NT type) { //AVDebug.Log("Firing "+type.ToString()); N n = new N(); n.type = type; Post(n); } public static void Post(NT type, object data) { N n = new N(); n.type = type; n.data = data; Post(n); } public static void Post(N note) { int typeInt = note.type.ToInt32(null); if (_listeners[typeInt] != null) { _listeners[typeInt](note); } } #region For Testing/Debugging only /// /// Used for debugging to outputs the number of listeners to have an idea of how many listeners are currently registered. /// public static void OutputNumOfListeners() { for (int i = 0; i < _listeners.Length; i++) { NT notificationType = (NT)(object)i; } } public static int GetListenerCount(NT notificationType) { var typeListeners = _listeners[notificationType.ToInt32(null)]; if (typeListeners != null) { return typeListeners.GetInvocationList().Length; } else { return 0; } } public static int GetTotalListenersCount() { int total = 0; for (int i = 0; i < _listeners.Length; i++) { total += GetListenerCount((NT)(object)i); } return total; } public static void Reset_USE_ONLY_FOR_UNIT_TESTS() { _listeners = new OnNotificationDelegate[System.Enum.GetValues(typeof(NT)).Length]; } #endregion }