duck

duck

Feb 26th, 2010
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3.  
  4. public class EventManager {
  5.  
  6.     private static Dictionary<Events, List<IEventListener>> listeners = new Dictionary<Events, List<IEventListener>>();
  7.  
  8.     // add listener to specified event
  9.     public static void AddListener(IEventListener obj, Events eventKey)
  10.     {
  11.         if (!listeners.ContainsKey(eventKey))
  12.         {
  13.             listeners.Add(eventKey, new List<IEventListener>());
  14.         }
  15.         listeners[eventKey].Add(obj);
  16.     }
  17.  
  18.    
  19.     // remove listener from specified event
  20.     public static void RemoveListener(IEventListener obj, Events eventKey)
  21.     {
  22.         List<IEventListener> listenerObjects = listeners[eventKey];
  23.         if (listeners != null)
  24.         {
  25.             if (listenerObjects.Contains(obj))
  26.             {
  27.                 listenerObjects.Remove(obj);
  28.             }
  29.         }
  30.     }
  31.  
  32.     // remove listener from all events
  33.     public static void RemoveListener(IEventListener obj)
  34.     {
  35.         foreach (KeyValuePair<Events, List<IEventListener>> entry in listeners)
  36.         {
  37.             RemoveListener(obj, entry.Key);
  38.         }
  39.     }
  40.  
  41.     // send event (with no data obj)
  42.     public static void Send(Events eventKey)
  43.     {
  44.         Send(eventKey, null);
  45.     }
  46.  
  47.     // send event
  48.     public static void Send(Events eventKey, object data)
  49.     {
  50.         foreach (IEventListener obj in listeners[eventKey])
  51.         {
  52.             obj.Event(eventKey, data);
  53.         }
  54.     }
  55. }
  56.  
  57. public interface IEventListener {
  58.     void Event(Events eventKey, object data);
  59. }
Add Comment
Please, Sign In to add comment