How to call an event from a child class

Hello everybody!

Just a short and simple question: how to call (.Invoke()) an event from a child class? I have acces to the event, but I’m not able to call his .Invoke() function. Here’s an example:

public class ParentClass : MonoBehaviour
{
    public delegate void MyDelegate();
    public event MyDelegate myEvent;
}

public class ChildClass : ParentClass
{
    private void Start()
    {
        myEvent.Invoke(); //This is not valid
    }
}

As a workaround, I’m just creating a proxy function in the parent class that calls the Invoke, so child class can call this function, but I don’t like it so much :stuck_out_tongue:

Perhaps re-visit some OOP and Unity tutorials.

myEvent.Invoke() will work - if it is initialized. Where do you initialize myEvent? If you want to invoke a superclass method, there is nothing special to it.

Also, I stringly recommend you use UnityEvents instead of Delegates and Events, as they integrate much better with Editor.

2 Likes

As far as I know, delegates and events doesn’t need to be initialized (opposite to UnityEvent). That’s the error I get

If I try to do the same from the parent class, all works perfectly

public class ParentClass : MonoBehaviour
{
    public delegate void MyDelegate();
    public event MyDelegate myEvent;

    private void Start()
    {
        myEvent.Invoke(); //This compiles
    }
}

public class ChildClass : ParentClass
{
    private void Start()
    {
        myEvent.Invoke(); //This DOESN'T compiles
    }
}

In this case I don’t need UnityEvents at all

That’s the way you have to do it when you use delegates with the event-modifier.

It’s actually correct what he said.
Using the event modifier only allows the declaring type to invoke and re-assign the event (the backing delegate actually).

Others, even subclasses, can only subscribe and unsubscribe feom it, unless methods for doing the above are provided.

The recommandation about unity events is highly subjective. I’d do the exact opposite… they are handy, but can be a nightmare.

3 Likes

Thanks @Suddoha , it seems that I can keep working and not re-visiting “some OOP tutorials” by now :stuck_out_tongue:

1 Like