如何使用保存 Mute/Unmute 按钮?

How to use save Mute/Unmute Button?

您好,我一直在研究这个问题,但我找不到解决问题的最佳方法。

所以问题是我的背景音乐启动 playing.I 有两个按钮。"On" 和 "Off"。我想将音乐静音,所以当我单击静音按钮时,它从 "On" 转到 "Off",当我更改场景并返回时,音乐 stops.But returns到带有文本 "On" 的按钮,但音乐仍然停止。 所以我的问题只是如何保存更改的按钮而不默认返回? 这是我的脚本:

public GameObject on;
public GameObject off;
public string sound;

Soundtrack music;
static bool isMuted;


void Awake()
{
    SoundCheck();


}
void Start()
{
    music = FindObjectOfType<Soundtrack>();
}
public void Off()
{
    if (isMuted == false)
     {
    on.gameObject.SetActive(false);
    off.gameObject.SetActive(true);
    music.s.Stop();
    isMuted = true;
    PlayerPrefs.SetString("Sound", "muted");
     }
}
public void On()
{    if(isMuted==true)
   {
    on.gameObject.SetActive(true);
    off.gameObject.SetActive(false);
    music.s.Play();
    isMuted = false;
    PlayerPrefs.SetString("Sound", "enabled");
   }
}
public void SoundCheck()
{
    sound = PlayerPrefs.GetString("Sound");

    if (sound == "enabled")
    {
        isMuted = false;
    }
    else if (sound == "muted")
    {
        isMuted = true;
    }
}

}

很简单。首先,最好在 PlayerPrefs 中保存 bool 类型而不是 string。 但是要解决您的问题,您只需添加

public void SoundCheck() { sound = PlayerPrefs.GetString("Sound"); if (sound == "enabled") { isMuted = false; } else if (sound == "muted") { isMuted = true; } on.gameObject.SetActive(isMuted); off.gameObject.SetActive(!isMuted); }

您需要更改 Start 函数中的 SoundCheck() 调用不唤醒! Start() 将在您返回场景时调用,但不会唤醒。

顺便说一句:

  1. 应该 bool 保存 PlayerPrefs,
  2. 想一个按钮,把sprite改成Sprite On和Sprite Off会更好。