using System; using System.Collections.Generic; namespace BlueWest.Tools { public sealed class EventManager { private readonly Dictionary> _subscribersList; private static EventManager _instance; public EventManager(Dictionary> subscribersList) { _subscribersList = subscribersList; _instance = this; } public EventManager() { _subscribersList = new Dictionary>(); _instance = this; } /// /// Adds a new subscriber to a certain event. /// /// listener. /// The event type. public void AddListener( EventListener listener ) where TEvent : struct { var eventType = typeof( TEvent ); if( !_subscribersList.ContainsKey( eventType ) ) _subscribersList[eventType] = new List(10000); //if( !SubscriptionExists( eventType, listener ) ) _subscribersList[eventType].Add( listener ); } /// /// Removes a subscriber from a certain event. /// /// listener. /// The event type. public void RemoveListener( EventListener listener ) where TEvent : struct { var eventType = typeof( TEvent ); List subscriberList = _subscribersList[eventType]; for (int i = 0; i /// Triggers an event. All instances that are subscribed to it will receive it (and will potentially act on it). /// /// The event to trigger. /// The 1st type parameter. public void TriggerEvent( TEvent newEvent ) where TEvent : struct { var type = typeof(TEvent); #if DEBUG if (!_subscribersList.ContainsKey(type)) { Console.WriteLine($"{type.FullName} has no actual trigger, fix it..."); return; } #endif List list = _subscribersList[type]; for (int i=0; i; casted.OnEvent( newEvent ); } } /// /// Checks if there are subscribers for a certain type of events /// /// true, if exists was subscriptioned, false otherwise. /// Type. /// Receiver. private bool SubscriptionExists( Type type, EventListenerBase receiver ) { List receivers; if( !_subscribersList.TryGetValue( type, out receivers ) ) return false; bool exists = false; for (int i=0; i( EventListener caller ) where EventType : struct { AddListener( caller ); } public void EventStopListening( EventListener caller ) where EventType : struct { RemoveListener( caller ); } } /// /// Static class that allows any class to start or stop listening to events /// public static class EventRegister { public delegate void Delegate( T eventType ); } /// /// TEvent listener basic interface /// public interface EventListenerBase { }; /// /// A public interface you'll need to implement for each type of event you want to listen to. /// public interface EventListener : EventListenerBase { void OnEvent( T eventType ); } }