c# - 为什么 PlayerPrefs 中没有减去数字?
问题描述
大家好在我的代码中,当你点击按钮时,应该减去一个数字并保存在 PlayerPrefs 中,减去数字,但不保存。我还了解到因为OnApplicationQuit方法退出游戏时会保存号码,如何让号码正常保存?
public class Chest_Money : MonoBehaviour
{
public int NumCharector;
public int money;
public int Rand;
public Text text;
public GameObject NotMoney;
public GameObject[] Charectors;
public GameObject Panel;
public GameObject Panel2;
public bool bla2;
void Start()
{
money = PlayerPrefs.GetInt("Money_S", 0);
}
private void Awake()
{
}
#if UNITY_ANDROID && !UNITY_EDITOR
private void OnApplicationPause(bool pause){
if(pause){
//PlayerPrefs.SetInt("Money_S" , money);
}
}
#endif
private void OnApplicationQuit()
{
PlayerPrefs.SetInt("Money_S" , money);
}
void Update()
{
PlayerPrefs.SetInt("Money_S", money);
text.text = "$:" + money;
if(bla2 == true){
Panel2.SetActive(true);
}
}
public void Chest(){
if(money >= 100){
money -= 100;
PlayerPrefs.SetInt("Money_S", money);
StartCoroutine(Wait2());
}
else {
NotMoney.SetActive(true);
StartCoroutine(Wait4());
}
}
IEnumerator Wait4(){
yield return new WaitForSeconds(2);
NotMoney.SetActive(false);
}
IEnumerator Wait2()
{
yield return new WaitForSeconds(0);
SceneManager.LoadScene("Scins");
}
}
解决方案
一般来说,您可以/应该使用PlayerPrefs.Save
强制保存某些检查点
默认情况下,Unity 在
OnApplicationQuit()
. 在游戏崩溃或过早退出的情况下,您可能希望在游戏中合理的“检查点”处编写 PlayerPrefs。此函数将写入磁盘可能会导致小问题,因此不建议在实际游戏过程中调用。
然后我还建议您使用类似的属性
private int _money;
public int money
{
get => _money;
set
{
_money = value;
PlayerPrefs.SetInt("Money_S");
PlayerPrefs.Save();
text.text = "$:" + money;
}
}
因此,它只会更新文本并在实际更改后保存值。
这样您就不需要更新文本或在Update
.
推荐阅读
- database - DBNavigator - 连接错误 - 无法识别的会话属性 - PyCharm 中的“v$session.program”
- python - 从 Python 中的键列表和值的多列表创建字典
- python - 如何更改 seaborn pairplot 中直方图的颜色(使用 jupyter 主题时)
- php - CAS协议认证cURL无表单
- python - 如何更新个人资料
- python - 具有多个入口点和一个配置文件的 Python 项目
- mysql - 如何在 # 之后和结束之前提取特定单词?MySQL
- python - 如何在python中检查bsc binance地址余额?
- python - pybind 中的私有模块函数
- keycloak - 如何在外部邮件模板中为 Keycloak 用户更新配置文件生成和使用登录操作令牌