Search Unity

Clicksound for many buttons across several scenes

Discussion in 'Scripting' started by Jorhoto, Oct 23, 2019.

  1. Jorhoto

    Jorhoto

    Joined:
    May 7, 2019
    Posts:
    26
    Hello,

    I am looking for a proper solution to let all the buttons in my application to emit different sounds (for the audio UI effects). I use like 10 scenes with one or more buttons each and I would need to play a sound (mostly click) after the OnClick event.

    A working method is to have a gameobject with an audiosource comp and call the appropiate function within each button, but, there isn't a better solution? I would like to get rid of:
    · The need of transitioning the gameobject accross all my scenes
    · Having to manually setup each button event call

    I tried scriptable objects, but they can't have attached the audiosource component.
    Any advice to solve this properly?

    Thanks!!
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    1,561
    If you have a bunch of buttons with similar styling (images/fonts/sounds/animations) you should make a prefab for that button, so that when you want to change the style (e.g. adding a sound) you can just change the prefab and all the buttons will "inherit" the change.

    But if you've already made all the buttons without using a prefab, you're probably not going to get around changing every single button manually. (Though you should think about replacing them all with a prefab. That will be more work now, but might save work later on.)

    As for making a given button play a sound, if you are concerned about it being difficult to modify the onClick events by hand, one alternative is to create a new MonoBehaviour that sets up the sound callback automatically. In some projects (particularly when I discovered I needed to add sounds to a bunch of buttons that weren't prefabs), I've used a script like this:

    Code (CSharp):
    1. [RequireComponent(typeof(Button))]
    2. public class ButtonSound : MonoBehaviour
    3. {
    4.     void Start()
    5.     {
    6.         Button button = GetComponent<Button>();
    7.         button.onClick.AddListener(PlaySound);
    8.     }
    9.  
    10.     void PlaySound()
    11.     {
    12.         // Do whatever you need to do to play the appropriate sound
    13.     }
    14. }
    If you can access the sound effect and audio source (or whatever wrappers you've written around them) somehow via singletons or a resource locator, then you can potentially code this component in such a way that it has no parameters and requires no setup at all--just attach the component to the button and you're done.

    (Of course, if you want different buttons to play different sounds, then you'll need to do a bit more work.)
     
unityunity