The simplest way to add Listener on a toggle ?


I would like to know what is the simplest way to add a Listener on a toggle. Something as simple as for the button. I want that clicking on it trigger a function. And clicking on it again trigger another function. I tried this :

theToggle.onValueChanged.AddListener (TheFunctionItShouldTrigger);

It didn’t work. Any idea please ?

I think the simplest way to add a listener would be through the inspector. You can add functions to be called from the “On Value Changed (Boolean)” listener through the inspector that can call a function from a script which is on an object that you specify. Then, in the function called from the event, unity passes the boolean for whether the toggle “.isOn” is true or false; so pass a boolean in the function parameters with whatever name you want to use inside the function. Make sure you select the dynamic bool version of the function in the inspector’s dropdown selector, or the value passed to the script’s function won’t change. Use the passed true or false boolean in an if/else statement and perform logic conditionally based on that. You could do some logic if it was true, else do some other logic, and that logic could be 2 different functions, or methods, or whatever you call them. I’d try to be more specific, but working with the inspector would require visual cues, and those are the best explained through videos. So, it might not make much sense yet, but if I’m understanding what you’re trying to do, Brackeys has a good answer in this video: SETTINGS MENU in Unity - YouTube