As answered here, I would like to know how to implement an EventManager with delegate instead of UnityAction for pass arguments. I tried but I did not succeed.
Also, can someone tell me if it's a better solution than following ? And is it possible to change this code for invoke listenners with a variable number of arguments?
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
namespace Assets.Scripts
{
[System.Serializable]
public class Event : UnityEvent<System.Object> { }
public class EventManager : MonoBehaviour
{
public static EventManager Instance;
private Dictionary<string, Event> _eventDictionary;
private void Awake()
{
...
}
public static void StartListening(string eventName, UnityAction<System.Object> listener)
{
Event thisEvent = null;
if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.AddListener(listener);
}
else
{
thisEvent = new Event();
thisEvent.AddListener(listener);
Instance._eventDictionary.Add(eventName, thisEvent);
}
}
public static void StopListening(string eventName, UnityAction<System.Object> listener)
{
if (Instance == null) return;
Event thisEvent = null;
if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.RemoveListener(listener);
}
}
public static void TriggerEvent(string eventName, System.Object arg=null)
{
Event thisEvent = null;
if (Instance._eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent.Invoke(arg);
}
}
}
}