How to set different volume in different scenes but still play the same song?

I’m thinking that I want the music in-game to be 100%, and the music in the Title/Menu/Game Over screen to be about 60% (kind of like how Super Mario World drops out instruments when you pause).

I’m stumped on how to do this. Here’s my logic so far:

If Scene = “Game”, then MusicPlayerVolume = 1
else if MusicPlayerVolume = .5

To clarify, I would like the music track to keep playing without interruption. The volume will decrease for the Title scene and Game Over scene.

What I’ve done is use a modified singleton on the music player. So you keep the same music player/audiosource, but before destroying the new audiosource, you set the current audio source volume to the audisource volume on the new level. Make sense?

public class BackgroundMusic : MonoBehaviour
    AudioSource audioSource;

    void Start()
        audioSource = GetComponent<AudioSource>();

    void SetupSingleton()
        var players = FindObjectsOfType<BackgroundMusic>();
        if (players.Length > 1)
            // Because FindObjectsOfType doesn't return the objects in specific
            // order, this bit of code will determine which player is the new one
            // and which player is the old one
            BackgroundMusic existingPlayer;
            if (players[0].GetBackgroundMusic().gameObject == this)
                existingPlayer = players[1];
            } else
                existingPlayer = players[0];
            existingPlayer.GetComponent<AudioSource>().volume = this.audioSource.volume;

You can also modfiy this method to change the track between levels while keeping the AudioSource throughout. Let me know if you want that bit of code added in.
1 Like

Thanks for this work so far!

I’m messing around with it and I got this error: (below the line BackgroundMusic existingPlayer; )

Assets\Scripts\BackgroundMusic.cs(24,28): error CS1061: ‘BackgroundMusic’ does not contain a definition for ‘GetBackgroundMusic’ and no accessible extension method ‘GetBackgroundMusic’ accepting a first argument of type ‘BackgroundMusic’ could be found (are you missing a using directive or an assembly reference?)


Could you please share the line to which the error message is referring? And is there a public GetBackgroundMusic in the BackgroundMusic class?