Documentation

Support

Unity Studio

Open Unity Studio

Unity Studio

Play audio when you click an object

Play audio when the user clicks on an object.
Read time 2 minutesLast updated 8 hours ago

In this example, you set up a Logic script to play audio when the user clicks on an object. Use these steps to set up similar interactions with audio in your scene. For example, you can play audio when the user clicks to open a door or play music on a radio.
1

Add an interactive object to your scene

  1. In the Hierarchy panel, select Add (+) and choose an object to add to your scene. For example, a cube or sphere.
  2. Select the object in the Hierarchy panel to open the Inspector panel.
  3. In the Inspector panel, make sure the object has a Collider component to detect user interaction. For example, a Box Collider or Sphere Collider.
    • If the object doesn't have a collider, select Add Component and add the appropriate collider.
2

Add audio to your object

  1. In your object's Inspector window, select Add Component > Audio Source. This adds an Audio Source component to your object, which plays audio clips in your scene.
  2. Find an audio clip in the My Assets folder or select Add Assets to import one.
  3. Drag your audio clip into your object's Audio Source component in the Audio Clip field.
  4. Disable Play On Awake so the audio doesn't play immediately when the scene starts.
3

Create and attach a Logic script to your object

  1. In the Hierarchy panel, select your object.
  2. Select Add Component (+).
  3. In the New Logic field, enter a name for your script and press Create and Edit. Unity Studio creates a new Logic script and automatically attaches it to your object. The Logic Editor opens so you can build your script.
4

Set up the initial logic in the Logic Editor

  1. In the Logic Editor, drag in a When node.
  2. Add a Clicked On event inside the When node's socket.
  3. Drag the
    me
    variable into the Clicked On node's socket. This variable references the object the script is attached to, so the event listens for clicks on this object.
5

Play the audio on click

  1. Drag an If node inside the When node.
  2. Move a Not node into the first socket of the If node.
  3. Drag the
    me
    variable into the Logic Editor, expand it, and choose Get Component > Audio Source > isPlaying. This creates a Boolean node that checks if the audio is currently playing.
  4. Drag the new me > Audio Source > isPlaying node into the Not node's socket.
  5. Add another
    me
    variable into the Logic Editor, expand it, and choose Get Component > Audio Source > Play.
  6. Place the me > Audio Source > Play node inside the If node.
Screenshot of an example Logic script that plays audio on click.

Example Logic script to play audio on click.

This logic checks if the audio isn't currently playing when the user clicks the object, and if so, it plays the audio. 7. Close the Logic Editor.

Additional resources