Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
public class GameEvent
{
}
public class EventMessenger
{
static EventMessenger _instance;
public static EventMessenger Instance
{
get
{
if (_instance == null)
{
_instance = new EventMessenger();
}
return _instance;
}
}
public delegate void EventDelegate<T>(T e) where T : GameEvent;
readonly Dictionary<Type, Delegate> _delegates = new Dictionary<Type, Delegate>();
public void AddListener<T>(EventDelegate<T> listener) where T : GameEvent
{
Delegate d;
if (_delegates.TryGetValue(typeof(T), out d))
{
_delegates[typeof(T)] = Delegate.Combine(d, listener);
}
else
{
_delegates[typeof(T)] = listener;
}
}
public void RemoveListener<T>(EventDelegate<T> listener) where T : GameEvent
{
Delegate d;
if (_delegates.TryGetValue(typeof(T), out d))
{
Delegate currentDel = Delegate.Remove(d, listener);
if (currentDel == null)
{
_delegates.Remove(typeof(T));
}
else
{
_delegates[typeof(T)] = currentDel;
}
}
}
public void Raise<T>(T e) where T : GameEvent
{
if (e == null)
{
throw new ArgumentNullException("e");
}
Delegate d;
if (_delegates.TryGetValue(typeof(T), out d))
{
EventDelegate<T> callback = d as EventDelegate<T>;
if (callback != null)
{
callback(e);
}
}
}
}
@insominx

This comment has been minimized.

Copy link

@insominx insominx commented Mar 15, 2013

I use this in all of my projects. Thank you!

@cesarvarela

This comment has been minimized.

Copy link

@cesarvarela cesarvarela commented Jun 30, 2013

I also like this code, has anyone had performance problems with this approach?

@jasonmirk

This comment has been minimized.

Copy link

@jasonmirk jasonmirk commented Oct 2, 2014

How do you Raise and event using this script? EventMessenger.Instance.Raise(e);
Doesnt work.

@SavedByZero

This comment has been minimized.

Copy link

@SavedByZero SavedByZero commented Oct 8, 2015

You don't need to use it as a singleton, do you? I'd rather not have every listener have to wade through every similar event of its kind before finding what it needs.

I've tried it as a regular class and it seems to work. Any performance pitfalls as a non-singleton?

@frideal

This comment has been minimized.

Copy link

@frideal frideal commented Jan 29, 2016

Nice~

@dibley1973

This comment has been minimized.

Copy link

@dibley1973 dibley1973 commented Feb 10, 2016

Awesome. I was using .Contains(...) but now using your technique. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment