- Home /
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:
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.
But in editor you can set some parameters. And if it requires signature "void f(bool b)" then you can't have one controller for multiple toggles, because you can't pass any info about which toggle it's about. And you need ugly workarounds. Seems weird. Very weird. So non unity way.
Answer by IASEnvy · Mar 01, 2015 at 03:02 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613175714im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
On Value changed event fired without the value changed. 1 Answer
Toggle UI c# 0 Answers
GUI Toggle and rotation??? 1 Answer
Using GUIToggle to on/off buttons! 5 Answers
Toggle Enabled/Disabled script? 2 Answers