Intro
In this beginner tutorial we will quickly cover how to add a sound effect and a button to our project. We will then trigger the sound effect to play when the button is pressed without typing any code. I am going to assume you have Unity installed and know how to create a project, if not there is plenty of great materiel out there to get you up and running.
Prep
Adding a button
Within the “Hierarchy” panel right-click and select UI => Button
Adding a sound file
Either drag a sound file from your file explorer into the “Assets” panel, or right-click in the Assets panel and select “Import new asset” and browse to the sound file. Unity support all of the major file formats that you would expect including .aif, .wav, .mp3, and .ogg.
Your sound file is now called an Audio Clip in Unity.
In this example I am going to be using my “click” Audio Clip
Adding an Audio Source to your project
You could add the Audio Source as a component of you canvas or button, in this case I am going to create is sesperately.
- Within the “Hierarchy” panel right-click and select Audio => Audio Source
- Rename it to something is reacquired, in this example I have used “snd_Click”
Linking the sound file to the button press
- Select your button in the “Hierarchy” panel.
- In the “Inspector” panel scroll down to the “Button (Script)” section and expand it if it is not already.
- Within the “On Click()” section click the + icon to add a new action.
- Click the select object icon in the field that currently says “None (object)” and browse and select your Audio Source
- Click the “No Function” drop down and select AudioSource => PlayOneShoot (AudioClip)
- Click the select audio click icon to the right of “None (Audio Clip)” and select your Audio Clip.
- You are done, give it a test 😄
Learning more
If you are new to Unity or would just like to learn more. Udemy have some great courses for a one time fee. Pluralsight have some great courses and they normally offer a free trial.
thanks for this. if i keep clicking the button it activates the sound again. any idea how to ensure the sound only gets activated once even if the button is clicked again – a way to disable the button after the first click? preferably in the editor and not through code
thanks
gary
It’s been a couple of years, so you probably found a solution by now but in case others have run into this issue:
By selecting “AudioSource.Play:” instead of “AudioSource.OneShot” you can make it so that only one source of a sound plays when the button is clicked, avoiding the overlapping cacophony that occurs with OneShot.
Thanks for sharing !
very well executed.
I worked my way through this perfectly. spot on!
That’s perfect!
that’s lame((( What if you have like 100 buttons for a detailed options menu?