- Home /
Generic class for Events and Event Listeners
Hi! I am trying to make a base class for events and event listeners, in order to override it in case I needed to create subclasses that take arguments of different types or classes.
By intuition, I tried to write it down like this, but intuition didn't work. Do you know if there's a way to do inheritance with events, or could you point me in the right direction, please?
Thanks, Filippo
[System.Serializable] public class Event1<T> : UnityEvent<T> { }
[System.Serializable] public class Event2<T, T> : UnityEvent<T, T> { }
public class EventListener : MonoBehaviour
{
public Event gEvent;
public UnityEvent response;
public Event1 response1;
public Event2 response2;
private void OnEnable()
{
gEvent.Register(this);
}
private void OnDisable()
{
gEvent.Unregister(this);
}
public virtual void OnEventOccurs()
{
response.Invoke();
}
public virtual void OnEventOccurs<T>(T arg)
{
response1.Invoke(arg);
}
public virtual void OnEventOccurs<T>(T arg1, T arg2)
{
response1.Invoke(arg1, arg2);
}
}
Unity can't serialize generics. Your Event1
and Event2
are pointless. Your subclasses must be non-generic.
So the events have to be configured beforehand. I just wanted to be sure.
Thank you anyway!
have you looked into UnityEvents? you can assign them in the inspector if that's what you want to do.
See the first two lines of the provided script
Your answer
Follow this Question
Related Questions
How can I get the Transform from an Object (target of UnityEvent)? 1 Answer
Convert Object to a Float 1 Answer
How to add dictionary keys with defined values to a list 1 Answer
Coroutine Chain of Events 1 Answer
Plantormer game architecture 0 Answers