- Home /
How can I add function to onClick event by code?
I've got problem with adding function to a button. I'm reloading scene many times on runtime and button loses its function. I can't add it from Inspector so i need to do it by code. I've tried this
void OnLevelWasLoaded(int level) {
if (level == 0) {
GameObject button = GameObject.Find("Sound");
Button b = button.GetComponent<Button>();
// b.onClick.AddListener(() => AudioSwitch());
b.onClick.AddListener(delegate { AudioSwitch(); });
}
}
but it does not work for me. How can I do that?
Can you add:
DontDestroyOnLoad(button);
And make sure next round, if the button is already there, do not add a second event.
Answer by jmorhart · Nov 04, 2015 at 10:52 PM
Try this:
b.onClick.AddListener(AudioSwitch);
Answer by elenzil · Nov 04, 2015 at 11:33 PM
your problem is including the paren's after AudioSwitch. AudioSwitch
means "use the function AudioSwitch itself here". AudioSwitch()
means "call AudioSwitch, and use whatever it returns here".
so assuming AudioSwitch() was a void function, your code is equivalent to
b.onClick.AddListener(() => null);
When I removed parentheses from AudioSwitch an error occured: Assets/Scripts/Audio$$anonymous$$onitor.cs(58,41): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement Thank you anyway! BTW, jmorhart answer works great :)