Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- public class EventDispatcher : ScriptBase
- {
- Dictionary<EventId, EventDelegate> events = new Dictionary<EventId, EventDelegate>();
- Dictionary<System.Delegate, EventDelegate> internalLookup = new Dictionary<Delegate, EventDelegate>();
- public void RegisterCallback<T>(EventId id, EventDelegate<T> callback) where T : EventArgs
- {
- EventDelegate internalDelegate = (e) =>
- {
- var convert = (T)e;
- callback(convert);
- };
- internalLookup[callback] = internalDelegate;
- EventDelegate handler;
- if (events.TryGetValue(id, out handler))
- {
- events[id] = handler += internalDelegate;
- }
- else
- {
- this.events[id] = internalDelegate;
- }
- }
- public void DeregisterCallback<T>(EventId id, EventDelegate<T> callback) where T : EventArgs
- {
- EventDelegate internalDelegate;
- if (internalLookup.TryGetValue(callback, out internalDelegate))
- {
- EventDelegate containingDelegate;
- if (events.TryGetValue(id, out containingDelegate))
- {
- containingDelegate -= internalDelegate;
- if (containingDelegate == null)
- {
- events.Remove(id);
- }
- else
- {
- events[id] = containingDelegate;
- }
- }
- internalLookup.Remove(callback);
- }
- }
- public void RaiseEvent<T>(EventId id, T eventArgs, bool needsListener = true) where T : EventArgs
- {
- EventDelegate del;
- if (events.TryGetValue(id, out del))
- {
- del.Invoke(eventArgs);
- }
- else if (needsListener)
- {
- Debug.LogWarning("Trying to raise an event with ID <" + id.ToString() + "> with no listeners on " + this.gameObject.name);
- }
- }
- }
- public delegate void EventDelegate<T>(T e) where T : EventArgs;
- public delegate void EventDelegate(EventArgs e);
- public enum EventId
- {
- Damaged,
- Died,
- AbilityCast,
- Healed,
- // Etc.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement