在 Unity 中,我为音量制作了一个工作滑块,以在场景更改时保持其值。游戏构建时,不再保存值

In Unity, I have made a working slider for volume that keeps it's value upon scene change. When the game is built, it no longer saves the value

我刚开始使用 Unity 和 C#,我会尽力解释情况并展示相关代码。

基本上我是在我的游戏中创建一个设置菜单。我的选项是全屏切换、分辨率下拉菜单、图形下拉菜单和音量滑块。除了音量滑块之外,所有这些设置都会在场景更改或游戏关闭和再次 运行 时保持选择。

在 Unity 中,音量滑块将保持其选中状态。只是一旦建成就不会出现在游戏中。相反,它会默认回到滑块的中间。

这里是相关代码。

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Audio;
    using UnityEngine.UI;
    using System.Linq;
    using TMPro;

    public class SettingsMenu : MonoBehaviour
    {
        public AudioMixer audioMixer;
        public Slider volumeSlider;

        private void Start()
        {
             volumeSlider.value = GetVolume();
        }

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

public float GetVolume()
{
    bool result = audioMixer.GetFloat("volume", out float value);
    if (result == true)
    {
        return value;
    }
    else
    {
        return -40f;
    }
}

现在正如我所说,这在 Unity 本身内一切正常,问题出现在我构建游戏时,更改场景意味着滑块只是默认设置。

如果您需要更多信息,请告诉我。提前致谢。

你很接近,使用 PlayerPrefs 存储最后设置的值。

像这样:

public class MyClass
{
    private const string VolumePreferenceKey = "preferred_volume";

    private const string VolumeKey = "volume";

    public AudioMixer Mixer;

    public float GetVolume()
    {
        if (Mixer == null)
        {
            Debug.LogWarning("Mixer property is not set !");

            return -1.0f;
        }

        if (Mixer.GetFloat(VolumeKey, out var volume))
        {
            return volume;
        }

        Debug.LogWarning("Mixer volume couldn't be retrieved !");

        return -1.0f;
    }

    public void SetVolume(float volume)
    {
        if (Mixer == null)
        {
            Debug.LogWarning("Mixer property is not set!");
            return;
        }

        if (!Mixer.SetFloat(VolumeKey, volume))
        {
            Debug.LogWarning("Mixer volume couldn't be set !");
            return;
        }

        PlayerPrefs.SetFloat(VolumePreferenceKey, volume);
    }
}

我写的很快,请根据您的需要进行调整。