c# - 在 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 未保存。我想知道复选框是否正确连接。这个我想不通!
解决方案
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
无论如何都不需要使用全局变量,因为您已经拥有PlayerPrefs
which 为您做同样的事情。
此外,您需要将 CheckBox 的状态设置为等于PlayerPrefs
启动游戏时的状态。
推荐阅读
- android - Flutters 资源加载速度比原生 Android 快
- php - 如何在 laravel 中添加休假计数器?
- java - 从linux机器连接到windows驱动器时出错[通过java程序]
- spring-boot - 如何在 bitbucket 上设置基于 java 11 的 Spring Boot 管道?
- c# - 如何按属性保存引用
- php - 如何使用 php 执行两个 Powershell 命令?
- c# - 如何在容器内使用 Coverlet 运行单元测试覆盖率报告?
- geopandas - Geopandas:获取一个覆盖 geopandas GeoDataFrame 区域的框,以使用它来反转地图
- jquery - 在模态框上显示一个弹出窗口
- react-native - 是否可以在 ExpoKit 中使用交互式推送通知?