Unity - 背景音乐通过带有 UI 滑块的场景

Unity - Background Music through scenes with UI slider

我在 Unity 中创建了一个具有 4 个不同场景(开始、登录、选项、游戏本身)的游戏。

使用空游戏对象(在开始场景中)和 DontDestroyOnLoad 函数,我设法让音乐在所有场景中播放,而无需在每个场景中停止或加载新的。

在选项场景中,有一个连接到主调音台的滑块,目前可以使用。

对我来说唯一的问题是滑块可以"interfere"与开始场景中的gameobject(背景音乐,应该通过滑块触发)。
如果有人可以帮助我,那就太棒了! :)

这里有一些摘录:

ChangeVolume class:

public AudioMixer audioMixer;

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

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 () {
}

我为你的 help/solutions 感到兴奋,也许还有更简单的! :-)

最简单的方法是使用 PlayerPrefs 并在其中保存声音值。每次您在 Awake() 中开始游戏时,您将设置该值,当滑块被触发时,您更改 PlayerPrefs 中的值并将其设置为 MusicBehaviour 实例。

我通过以下方式编辑我的脚本解决了我的问题:

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;

我也删除了我的混音器,因为不再需要它了。而且效果很好! :-)