Search Unity

Question Proper way to add audio?

Discussion in 'UI Toolkit' started by goldbug, Nov 7, 2022.

  1. goldbug

    goldbug

    Joined:
    Oct 12, 2011
    Posts:
    767
    I would like to add audio to my game UI.

    For example, whenever I click on buttons, I want a "click" sound, whenever I open a window I want a swoop-in sound, etc.

    In "dragon crashers", they are doing it manually. In every event handler, they just add a play sound line of code. This is not great, it means adding that line of code in dozens of places, and having to manually enforce consistency. It is a cross-cutting concern that I would have to sprinkle all over my game logic.

    With the introduction of uss animations, I was able to remove most of the animation logic from my game logic and keep it consistent across all screens.

    It would be better if I could specify sound as part of the stylesheet too, just like animations. For example, I would do something along the lines of:

    Code (csharp):
    1.  
    2. .unity-button:active {
    3.     --audio-play: 'click'
    4. }
    5.  
    Does anyone have a suggestion for how to implement something like that? Does anyone have a cleaner way to add sound effects than putting it in all handlers?
     
  2. noirb

    noirb

    Joined:
    Apr 10, 2014
    Posts:
    84
    If you're using the same sound across many of the same kind of button, then you might consider subclassing the Button class and adding the sound playing logic there. Then every instance of your CustomButton would play the same sound (or perhaps you could find a way to parameterize which sound the button played, e.g. by specifying the filename in a UXML property and loading it with Resources.Load).
     
    goldbug likes this.
  3. goldbug

    goldbug

    Joined:
    Oct 12, 2011
    Posts:
    767
    I suppose that would work, but then I would have to subclass radios, toggle, dropdown, create a component for windows, and repeat that logic for every type of component and every event I want to add sound to.

    Not ideal, but it is better than nothing I supposed. Thank you for the suggestion.