Search code examples
c#unity-game-engineeventsdelegatesanonymous-methods

How to subscribe to an event with a delegate


I would like to subscribe to an event so that when the event fires I can execute a delegate or anonymous function.

Subscribing to events with methods is easy I can just type the method name, this works fine:

UnityEngine.UI.Toggle tgl;
tgl.onValueChanged += myMethod;

But I cannot subscribe a delegate using the same syntax. This will not work:

tgl.onValueChanged += delegate{ Debug.Log("Bang!"); };

I researched this Q&A which suggested I try the following approach but this is also not working:

tgl.onValueChanged += (object sender, EventArgs e) => { Debug.Log("Bang!"); };

How can I make this work?


Solution

  • You need to look at what type onValueChanged is, before trying to subscribe to it. This is its declaration, taken from here.

    public UI.Toggle.ToggleEvent onValueChanged;
    

    Its type is a ToggleEvent, which is a class, not an event nor a delegate. Therefore, you cannot use the += operator on it.

    You should call AddListener, like the examples did:

    tgl.onValueChanged.AddListener(delegate { ... })