- Home /
Adding a listener to Toggle.onValueChanged via Script
Hello,
I was trying to add a listener on a Toggle Button but i am not able to write that. Can anybody please help me. Here is what i am doing
Toggle sound = GameObject.Find("soundOnOff").GetComponent();
sound.onValueChanged.AddListener(gameSoundStatusChanged); // --- Error
and the function is
public void gameSoundStatusChanged()
{....}
it says .addlistener has some invalid parameters. Cause it asks for parameter of type UnityAction function. Please help me on how to write the function in given syntax.
Answer by batteryyrettab · Oct 24, 2014 at 07:20 AM
I just had the same issue. You just need to pass a float parameter into your method. eg.
public Slider myMusicVolumeSlider;
AudioSource myBGMusic;
void Start ()
{
myBGMusic = GetComponent<AudioSource>();
myMusicVolumeSlider.value = 0.2f;
myMusicVolumeSlider.onValueChanged.AddListener(RaiseVolume);
}
void Update ()
{
//I Don't want to run this every frame....
//myBGMusic.volume = myMusicVolumeSlider.value;
}
public void RaiseVolume(float value)
{
myBGMusic.volume = myMusicVolumeSlider.value;
//Or even just... myBGMusic.volume = value;
}
Im not sure how this works with a Toggle like in the original post. What would the listener have to accept? A callback?
See the answer Elvira_Z provided. It is the more correct answer to your question. I provided one for a Slider rather than a Toggle component but the principle is the same.
Answer by Elvira_Z · Apr 29, 2016 at 08:39 AM
Only just like this:
Toggle sound = GameObject.Find("soundOnOff").GetComponent(); sound.onValueChanged.AddListener(gameSoundStatusChanged);
public void gameSoundStatusChanged(bool isclick) {....}
Answer by Ignorant · Jun 11, 2018 at 03:53 PM
your method gameStatusChanged() needs to take bool param so change it to: gameStatusChanged(bool newValue) and it will work fine
Your answer
![](https://koobas.hobune.stream/wayback/20220613164059im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Toggle between scripts with a script? 2 Answers
[C#]Toggle Run on/off 2 Answers
Distribute terrain in zones 3 Answers