首页 > 解决方案 > 在 Unity C# 中使用复选框和 playerprefs 切换布尔值

问题描述

我正在尝试在 Unity UI 中创建一个复选框,将 bool 无尽的游戏返回为“真”,如果是定时游戏,则返回“假”。我想用 PlayerPrefs 做到这一点。我知道 PP 只支持 int、float 和 strings。我创建了一个符合 1 的函数。

我有一个游戏管理器来处理游戏的整体状态,这个游戏对象是我游戏中唯一一个在加载时不会被破坏的游戏对象。

到目前为止,游戏管理器有一个 bool 'endless' 被初始化为

endless = PlayerPrefs.GetInt("Endless", 1) == 0;

在启动函数中。

现在我有一个包含复选框的选项菜单,在这个脚本中如下:

public void OnToggleEndless()
{
    if (endLessToggle.isOn)
    {
        PlayerPrefs.SetInt("Endless", manager.endless ? 1 : 0);
        
        print("Endless Button ticked");
    }
    else 
    {
        PlayerPrefs.SetInt("Endless", manager.endless ? 0 : 0);
        print("Endless Button unticked");            
    }
    
}

但是当我连接它,玩游戏并进入选项菜单并勾选“无尽游戏”时,什么也没有发生。我试图把 OnToggleEndless(); Update 中的方法,但这只是给了我无穷无尽的打印行(“Endless Button ticked”);消息,PlayerPrefs 未保存。我想知道复选框是否正确连接。这个我想不通!

标签: c#unity3d

解决方案


PlayerPrefs 未保存

似乎有错误的保存PlayerPrefs是您确定要实际检查manager.endless而不是endLessToggle.isOn.

因为状态的endLessToggle.isOn变化取决于您是否启用或禁用了复选框。但是manager.endless从不改变的状态并在游戏开始时设置为真/假。

这导致您PlayerPrefs在切换复选框时实际上并未更改变量。

例子:

private void Start() {
    // Check if we enabled or disabled the endlessToggle Checkbox last time we played
    // and set the checkbox accordingly.
    endLessToggle.isOn = (PlayerPrefs.GetInt("Endless", 1) == 0);
}

// Call when we toggle the Checkbox.
public void OnToggleEndless() {
    // Get the current state of our toggle button.
    int enable = endLessToggle.isOn ? 1 : 0;
    // Log result into console to test it.
    Debug.Log("We set Endless to: " + enable);
    // Set the PlayerPrefs equal to our current state.
    PlayerPrefs.SetInt("Endless", enable);
}

我认为您GameManager无论如何都不需要使用全局变量,因为您已经拥有PlayerPrefswhich 为您做同样的事情。

此外,您需要将 CheckBox 的状态设置为等于PlayerPrefs启动游戏时的状态。


推荐阅读