Playing a sound on all button presses?
Hello,
I know I can add a sound to a button being pressed, but I was wondering if I could set some global rule that whenever a button is pressed, it plays the same sound. Just want to see if I can do this without having to go to every single button throughout the whole scene and add a sound manually.
Thank you
That is one choice. Or you could also add button listener to each button from code, collect buttons when game starts, then add the listener. Or add some script to each button prefab (unless you have tons of unique) that adds button onClick listener on start, that plays sound on click event.
Answer by eses · Aug 13, 2018 at 11:12 AM
Hi @shapirog.
I wrote a comment too, but here is one solution;
void Start ()
{
buttons = GameObject.FindObjectsOfType<Button>();
foreach (var b in buttons) {
UnityAction l = delegate { OnClick(); };
b.onClick.AddListener(l);
}
}
void OnClick()
{
Debug.Log("Click!");
}
foreach (var b in buttons) {
b.onClick.AddListener( OnClick );
}
This, as well as hellium's addition, worked great. Thank you!