How to Use Audio Source in Unity: Simple Guide
In Unity, use the
AudioSource component to play sounds by attaching it to a GameObject and assigning an AudioClip. Control playback with methods like Play(), Pause(), and Stop() on the AudioSource.Syntax
The AudioSource component is added to a GameObject to play audio clips. You assign an AudioClip to it and control playback with methods.
AudioSource.Play(): Starts playing the assigned clip.AudioSource.Pause(): Pauses playback.AudioSource.Stop(): Stops playback.AudioSource.clip: The audio clip to play.
csharp
AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = yourAudioClip; audioSource.Play();
Example
This example shows how to add an AudioSource to a GameObject, assign an AudioClip, and play it when the game starts.
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 soundClip plays once from the GameObject.
Common Pitfalls
Common mistakes include forgetting to assign an AudioClip, not adding the AudioSource component, or trying to play audio before the clip is loaded.
Also, ensure the volume is not zero and the AudioSource is not muted.
csharp
/* Wrong way: No AudioClip assigned */ AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.Play(); // No sound plays /* Right way: Assign AudioClip before playing */ audioSource.clip = yourAudioClip; audioSource.Play();
Quick Reference
| Property/Method | Description |
|---|---|
| AudioSource.clip | The audio clip to play |
| AudioSource.Play() | Starts playing the clip |
| AudioSource.Pause() | Pauses playback |
| AudioSource.Stop() | Stops playback |
| AudioSource.volume | Controls the volume (0 to 1) |
| AudioSource.loop | Set to true to loop the clip |
Key Takeaways
Add an AudioSource component to a GameObject to play sounds.
Assign an AudioClip to the AudioSource before calling Play().
Use Play(), Pause(), and Stop() methods to control audio playback.
Check volume and mute settings if audio does not play.
Loop property allows repeating sounds automatically.