Unity 101 : Playing a sound when a UI button is pressed

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

Unity add button sound

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

Unity add button sound

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.
Unity add button sound
  • Click the select object icon in the field that currently says “None (object)” and browse and select your Audio Source
Unity add button sound
  • Click the “No Function” drop down and select AudioSource => PlayOneShoot (AudioClip)
Unity add button sound
  • Click the select audio click icon to the right of “None (Audio Clip)” and select your Audio Clip.
Unity add button sound
  • 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.

3 thoughts on “Unity 101 : Playing a sound when a UI button is pressed”

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

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.