Adding audio to a Unity 2D

 Adding audio to a Unity 2D project is pleasantly straightforward once you know the workflow. You’re essentially doing three things: importing audio, assigning it to an Audio Source, and triggering it through code or the Inspector.

Below is a clean, practical guide you can follow right away.


🎵 1. Import Your Audio File

Unity supports WAV, MP3, OGG, and more.

  • Drag your audio file into the Assets folder.
  • Select the file and check the Inspector:
    • Load Type: Compressed In Memory (good for music) or Decompress On Load (good for short sound effects)
    • Loop: Enable if it’s background music

🔊 2. Add an Audio Source to a GameObject

Every sound in Unity needs an Audio Source.

  • Select the GameObject that should play the sound
    (e.g., your player, an empty object called “MusicPlayer”, etc.)
  • Go to Add Component → Audio → Audio Source
  • Drag your audio clip into the AudioClip field
  • Choose:
    • Play On Awake if you want it to start automatically
    • Loop if it’s background music

🧩 3. Play Audio Through Script (Optional)

If you want to trigger sounds through gameplay—jumping, shooting, collecting items—use a script.

Example: Play a sound when something happens

public class PlaySound : MonoBehaviour
{
    public AudioSource audioSource;

    void Start()
    {
        // Optional: automatically play at start
        // audioSource.Play();
    }

    public void PlayClip()
    {
        audioSource.Play();
    }
}
/////////////////////////
using UnityEngine;

public class Sounds : MonoBehaviour
{
    public AudioSource audioSource;
    public AudioClip clip1, clip2, clip3;
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void PlaySound1()
    {
        audioSource.PlayOneShot(clip1);
    }
    public void PlaySound2()
    {
        audioSource.PlayOneShot(clip2);
    }
    public void PlaySound3()
    {
        audioSource.PlayOneShot(clip3);
    }

}

Attach the script to a GameObject, then drag the Audio Source into the audioSource field in the Inspector.


🔁 4. Playing One‑Shot Sound Effects

For sound effects that shouldn’t interrupt each other:

public AudioSource audioSource;
public AudioClip sfx;

void PlaySFX()
{
    audioSource.PlayOneShot(sfx);
}

🎮 5. Triggering Audio with Collisions or Input

Example: Play sound when player presses space

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        audioSource.Play();
    }
}

Example: Play sound on collision

void OnCollisionEnter2D(Collision2D collision)
{
    audioSource.Play();
}

Comments