Add listener to a UI toggle through script

I am trying to populate a list of toggles automatically when the game starts, and I have managed to get it all working except one thing: I can’t figure out how to add an event listener to the toggle. All of the information I could find gave me errors, because I’m trying the make the toggle call a custom function when the value is changed.

The toggle looks like this in the inspector when I do it manually:

38236-pos.png

I know I have to set the object the script is on, the function, and the value through script - but I have no idea how to do that.

toggle.onValueChanged.AddListener((on)=>{x = on;});

The toggle expects a function with this signature:

void f(bool x);

So, anything with a void return and a bool argument. It will call whatever you put as AddListener’s argument. The argument here is a lambda expression that takes the toggle’s state and assign it to x. With lambdas, you don’t need to specify a type for the argument if the compiler can figure it out, and you don’t have to put return x in this case, either. So, whenever the toggle is changed, the listener will call the lambda function, and mine will assign the toggle’s state to x.