How to Add Audio in Unity: Simple Steps to Play Sounds
To add audio in Unity, attach an
AudioSource component to a GameObject and assign an AudioClip to it. Then, use AudioSource.Play() in your script to play the sound.Syntax
In Unity, audio is played using the AudioSource component and an AudioClip. The basic syntax involves:
- Adding an
AudioSourcecomponent to a GameObject. - Assigning an
AudioClip(your sound file) to theAudioSource. - Calling
AudioSource.Play()in a script to start the sound.
csharp
AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = yourAudioClip; audioSource.Play();
Example
This example shows how to play a sound when the game starts. It assumes you have an audio file imported as an AudioClip in your project.
csharp
using UnityEngine; public class PlaySoundOnStart : MonoBehaviour { public AudioClip soundClip; private AudioSource audioSource; void Start() { audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = soundClip; audioSource.Play(); } }
Output
When the game starts, the assigned audio clip plays once from the GameObject.
Common Pitfalls
Common mistakes when adding audio in Unity include:
- Not assigning an
AudioClipto theAudioSource, so no sound plays. - Forgetting to add an
AudioSourcecomponent before callingPlay(). - Trying to play audio before the clip is loaded or assigned.
- Setting the volume to zero or muting the audio unintentionally.
Always check that your AudioClip is assigned and the AudioSource is enabled.
csharp
/* Wrong way: No AudioSource component added */ // audioSource.Play(); // This will cause an error /* Right way: Add AudioSource first */ audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = yourAudioClip; audioSource.Play();
Quick Reference
| Step | Action | Description |
|---|---|---|
| 1 | Add AudioSource | Attach an AudioSource component to your GameObject. |
| 2 | Assign AudioClip | Set the AudioClip property to your sound file. |
| 3 | Play Sound | Call AudioSource.Play() in your script to play the audio. |
| 4 | Adjust Settings | Optionally set volume, loop, and spatial blend on AudioSource. |
Key Takeaways
Add an AudioSource component to a GameObject to play audio.
Assign an AudioClip to the AudioSource before playing.
Use AudioSource.Play() to start the sound.
Check that volume is not zero and AudioSource is enabled.
Common errors come from missing AudioSource or AudioClip assignments.