Home > Net >  Is there a way to play an audio clip on ANY onClick() call?
Is there a way to play an audio clip on ANY onClick() call?

Time:01-15

I have a lot of buttons in my game and want to play a sound for if any of them are clicked. I know I can do this by going through and doing something like AudioSource.PlayOneShot() but the problem is that having to go through and add that call to every button in my game seems tedious, but if there is a quick way to do this that'd be great. I think I'm looking for a way to simply subscribe to EVERY button's onClick event.

CodePudding user response:

Just a trick to replace all the Button in your project with a custom class.

Suggest to backup first.

  1. Create your custom button script
public class CustomButton : UnityEngine.UI.Button
{
    public override void OnPointerClick(PointerEventData eventData)
    {
        base.OnPointerClick(eventData);
        
        //Play your sound here
    }
}
  1. Open this file <project root folder>\Library\PackageCache\[email protected]\Runtime\UI\Core\Button.cs.meta.

    Remember the guid. <guid-1>

  2. Open CustomButton.cs.meta, the meta file of the script created in step 1.

    Remember the guid. <guid-2>

  3. Now using your favorite text editor to do a full-text search-and-replace <guid-1> with <guid-2> in folder <project root folder>\Assets with the following extension: *.asset|*.prefab|*.unity

CodePudding user response:

If you are using javascript, then this can be achieved by adding event listener to DOM elements(buttons) sharing a common element name.

document.getElementsByName('btnName').forEach(item => item.addEventListener('click', callbackFunction, false));

Same can be done using class property also.

var items = document.querySelectorAll('.className');
items.forEach(item => item.addEventListener('click', callbackFunction, false));
  •  Tags:  
  • Related