vitoscal
vitoscal

Reputation: 41

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! :-)

Upvotes: 1

Views: 1629

Answers (2)

vitoscal
vitoscal

Reputation: 41

I fixed my problem through editing my scripts in the following way:

Music Behaviour class:

 void Update () {
         float vol = ChangeVolume.vol;
         this.gameObject.GetComponent<AudioSource> ().volume = vol;
     }

Change Volume class:

public void setVolume(float volume){
    vol = volume;
}

public static float vol = 1.0f;

I also deleted my audiomixer due to not needing it anymore. And it works just fine! :-)

Upvotes: 0

Ivan Kaloyanov
Ivan Kaloyanov

Reputation: 1748

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.

Upvotes: 2

Related Questions