[ad_1]
My query is extra C# than Unity, nevertheless it depends on a Unity particular delegate, additionally, sorry if the title is just not that clear to what I am attempting to do.
I’ve applied a easy occasion supervisor which makes use of a dictionary of <EventName,UnityEvent<object>>.
It really works nice for what I need, however because it encapsulates a UnityEvent<object> it converts my parameters to object as a substitute of their concrete lessons.
I’ve tried doing the next to have the ability to register the delegate for the occasions utilizing the concrete sort parameter.
Created an interface and BaseEventData class:
public interface IEventData {}
public summary class BaseEventData : IEventData {}
Created a customized UnityEvent for this kind parameter
[Serializable]
public class CustomDataEvent<T> : UnityEvent<T> the place T : IEventData {}
Then I’ve my dictionary:
protected inner Dictionary<EventName, CustomDataEvent<IEventData>> CustomEventDictionary;
What I need to have the ability to do is:
EventManager.StartListening<DummyEventData>(EventName.DummyEvent, DummyEventData knowledge => Methodology(knowledge));
In order that my methodology/delegate can use DummyEventData because the parameter sort as a substitute of IEventData/object after which have to forged it to DummyEventData.
What I’ve tried doing on my register methodology:
public static void StartListening<T>(EventName eventName, UnityAction<T> listener) the place T : IEventData
{
if (Occasion.CustomEventDictionary.TryGetValue(eventName, out var thisEvent))
{
thisEvent.AddListener(listener);
}
else
{
thisEvent = new CustomDataEvent<IEventData>();
thisEvent.AddListener(listener);
Occasion.CustomEventDictionary.Add(eventName, thisEvent);
}
}
Nevertheless, this isn’t potential, the compiler says that UnityAction<T> is just not assignable to UnityAction<IEventData>, I’ve examine covariance and contravariance which appears to be the difficulty right here, however as this entails UnityAction I couldn’t implement the answer I discovered on this query, is there a approach, if any, to attain what I am attempting to?
[ad_2]

Leave a Reply