0
0
Unityframework~5 mins

Background music management in Unity

Choose your learning style9 modes available
Introduction

Background music makes games more fun and immersive. Managing it well helps keep the music playing smoothly and at the right times.

You want music to play continuously while the player moves between game scenes.
You want to start or stop music when the player pauses or resumes the game.
You want to change music based on game events, like entering a battle or a calm area.
You want to control music volume or mute it from settings.
You want to avoid multiple music tracks playing over each other.
Syntax
Unity
using UnityEngine;

public class MusicManager : MonoBehaviour
{
    public AudioSource musicSource;

    void Start()
    {
        musicSource.Play();
    }

    public void StopMusic()
    {
        musicSource.Stop();
    }

    public void SetVolume(float volume)
    {
        musicSource.volume = volume;
    }
}

AudioSource is the component that plays sound in Unity.

Use Play() to start music and Stop() to stop it.

Examples
Starts playing the assigned music clip.
Unity
musicSource.Play();
Stops the music immediately.
Unity
musicSource.Stop();
Sets the music volume to half.
Unity
musicSource.volume = 0.5f;
Makes the music repeat automatically.
Unity
musicSource.loop = true;
Sample Program

This script plays background music that loops forever. It keeps playing when you change scenes. You can pause, resume, and change volume safely.

Unity
using UnityEngine;

public class BackgroundMusicManager : MonoBehaviour
{
    public AudioSource musicSource;

    void Awake()
    {
        DontDestroyOnLoad(gameObject); // Keep music playing across scenes
    }

    void Start()
    {
        musicSource.loop = true; // Repeat music
        musicSource.Play();
    }

    public void PauseMusic()
    {
        musicSource.Pause();
    }

    public void ResumeMusic()
    {
        musicSource.UnPause();
    }

    public void SetMusicVolume(float volume)
    {
        musicSource.volume = Mathf.Clamp01(volume); // Keep volume between 0 and 1
    }
}
OutputSuccess
Important Notes

Attach this script to a GameObject with an AudioSource component that has your music clip.

Use DontDestroyOnLoad to keep music playing when switching scenes.

Control volume between 0 (silent) and 1 (full volume) to avoid errors.

Summary

Background music improves game experience by playing sound continuously.

Use AudioSource component to play, stop, pause, and control music volume.

Keep music playing across scenes with DontDestroyOnLoad.