Last active
August 29, 2015 14:19
-
-
Save romainPechot/b618bace6beebf910749 to your computer and use it in GitHub Desktop.
Generic Event Listener. Example : http://imgur.com/a4yVrQ1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
public static class EventListener | |
{ | |
private const int listListenerSizeMin = 10; | |
public static bool debugCalls = false; | |
// player events delegate | |
public delegate void Callback(object newValue); | |
// list of listeners | |
private static Dictionary<string, List<Callback>> callbacks = new Dictionary<string, List<Callback>>(21); | |
// sub | |
public static void Add(object eventValue, Callback callback) | |
{ | |
string key = GenerateKey(eventValue); | |
// no key ? >> add list with new key | |
if(!callbacks.ContainsKey(key)) callbacks.Add(key, new List<Callback>(listListenerSizeMin)); | |
// not in list >> add to list | |
if(!callbacks[key].Contains(callback)) callbacks[key].Add(callback); | |
}// Add() | |
// un-sub | |
public static void Remove(object eventValue, Callback callback) | |
{ | |
string key = GenerateKey(eventValue); | |
// has key >> remove | |
if(callbacks.ContainsKey(key)) callbacks[key].Remove(callback); | |
}// Remove() | |
// launch event | |
public static void Launch(object eventValue){Launch(eventValue, null);} | |
public static void Launch(object eventValue, object newValue) | |
{ | |
string key = GenerateKey(eventValue); | |
// has key ? | |
if(callbacks.ContainsKey(key)) | |
{ | |
List<Callback> listCallback = callbacks[key]; | |
// callbacks | |
for(int i = 0; i < listCallback.Count; i++) listCallback[i](newValue); | |
// debug ? | |
if(debugCalls) DebugEventLaunch(key); | |
} | |
}// Launch() | |
private static void DebugEventLaunch(string key) | |
{ | |
Debug.Log(key + "\n" + TimeManager.TIME.ToString("F0") + "," + TimeManager.Tick()); | |
}// DebugEventLaunch | |
private static string GenerateKey(object eventType){return eventType.GetType().ToString() + eventType.ToString();} | |
}// EventListener |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment