How to Play Background Music in Unity: Simple Steps
To play background music in Unity, add an
AudioSource component to a GameObject and assign an AudioClip to it. Then call audioSource.Play() in your script to start the music.Syntax
In Unity, background music is played using the AudioSource component and an AudioClip. You attach an AudioSource to a GameObject, assign the music clip, and control playback with script.
- AudioSource: Component that plays audio.
- AudioClip: The music file (e.g., mp3, wav) to play.
- Play(): Method to start playing the assigned clip.
csharp
AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = yourAudioClip; audioSource.Play();
Example
This example shows how to play background music automatically when the game starts. It uses a GameObject with an AudioSource and plays the assigned AudioClip on start.
csharp
using UnityEngine; public class BackgroundMusic : MonoBehaviour { public AudioClip musicClip; private AudioSource audioSource; void Start() { audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = musicClip; audioSource.loop = true; // Loop the music audioSource.Play(); } }
Output
Background music starts playing and loops continuously when the game runs.
Common Pitfalls
Common mistakes when playing background music in Unity include:
- Not assigning an
AudioClipto theAudioSource, so nothing plays. - Forgetting to set
loop = trueif you want continuous background music. - Adding multiple AudioSources playing the same clip causing overlapping sounds.
- Not adjusting volume or muting other sounds unintentionally.
Always check your AudioSource settings and clip assignment.
csharp
/* Wrong: No clip assigned */ AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.Play(); // Nothing plays because clip is null /* Right: Assign clip and loop */ audioSource.clip = yourAudioClip; audioSource.loop = true; audioSource.Play();
Quick Reference
Tips for playing background music in Unity:
- Use
AudioSourcecomponent on a dedicated GameObject. - Assign your music file as an
AudioClipin the inspector or via script. - Set
loop = truefor continuous play. - Control volume with
audioSource.volume. - Call
audioSource.Play()to start music.
Key Takeaways
Add an AudioSource component and assign an AudioClip to play background music.
Set loop to true on AudioSource to keep music playing continuously.
Call Play() on AudioSource to start the music.
Avoid missing clip assignment to prevent silent AudioSource.
Use a dedicated GameObject for background music to manage it easily.