0
0
UnityHow-ToBeginner ยท 3 min read

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 AudioSource component to a GameObject.
  • Assigning an AudioClip (your sound file) to the AudioSource.
  • 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 AudioClip to the AudioSource, so no sound plays.
  • Forgetting to add an AudioSource component before calling Play().
  • 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

StepActionDescription
1Add AudioSourceAttach an AudioSource component to your GameObject.
2Assign AudioClipSet the AudioClip property to your sound file.
3Play SoundCall AudioSource.Play() in your script to play the audio.
4Adjust SettingsOptionally 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.