简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM