Search code examples
c#unity-game-engineaudiouislidermixer

Unity - Background Music through scenes with UI slider


I created a game in Unity with 4 different scenes (start, login, options, game itself).

With an empty game object (in the start scene) and the DontDestroyOnLoad function I have managed to have the music played throughout all scenes without stopping or loading new in every scene.

In the options scene there is a slider hooked to an master audio mixer, which works so far.

The only problem for me is that the slider can "interfere" with the gameobject in the start scene (background music, which should be triggered through the slider).
It would be awesome if someone could help me! :)

Here some extracts:

ChangeVolume class:

public AudioMixer audioMixer;

public void setVolume(float volume){
    audioMixer.SetFloat ("volume", volume);
}

and

MusicBehaviour class:

//Play global
private static MusicBehaviour instance = null;
    public static MusicBehaviour Instance {
        get {
              return instance;
        }
    }

void Awake()
{
    if (instance != null && instance != this) {
        Destroy (this.gameObject);
        return;
    } else {
        instance = this;
    }
    DontDestroyOnLoad (this.gameObject);
}

//Play Global End

//Update is called once per frame
void Update () {
}

I'm excited for your help/solutions, maybe there is a simpler one! :-)


Solution

  • The easiest approach is to use PlayerPrefs and save the sound value there. Every time you start the game in Awake() you will setup the value and when slider is triggered you change the value in PlayerPrefs and set it to the MusicBehaviour instance.