1

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?

mrVentures
  • 121
  • 1
  • 8

1 Answers1

0

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 { ... })
Sweeper
  • 213,210
  • 22
  • 193
  • 313