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.
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 😄
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.