Unity中PlayerPrefs.GetFloat自动变为0的问题求助
问题:PlayerPrefs存储的Float值莫名变为0
我的Float值会自动变为0,但我并未手动设置它,且这是唯一调用.SetFloat方法的脚本。已经为此困扰3小时了。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Scriptname : MonoBehaviour { private string Words; public float ShowPrefs; private void Start() { PlayerPrefs.DeleteKey("C"); Words = this.gameObject.name; PlayerPrefs.SetFloat(Words, 2); PlayerPrefs.Save(); } private void Update() { ShowPrefs = PlayerPrefs.GetFloat(Words); if (PlayerPrefs.GetFloat(Words) == 2) { PlayerPrefs.DeleteKey(Words); } if (PlayerPrefs.GetFloat(Words) == 1) { PlayerPrefs.SetFloat(Words, 1); } } private void OnTriggerStay(Collider other) { if (other.gameObject.name == Words) { PlayerPrefs.SetFloat(Words, 1); PlayerPrefs.Save(); } else { PlayerPrefs.SetFloat(Words, 2); PlayerPrefs.Save(); } } }
不知为何,PlayerPrefs.GetFloat(Words)会自动变为0,即使多次重启Unity也无法解决。已在谷歌上搜索但未找到答案,在此求助,感谢帮忙!
问题根源
你代码里的核心问题出在Update方法中:
- 当
PlayerPrefs.GetFloat(Words)等于2时,你执行了PlayerPrefs.DeleteKey(Words),直接删除了这个键。 - 之后再调用
PlayerPrefs.GetFloat(Words)时,因为键已经不存在,Unity会返回默认值0,这就是你看到值莫名变0的原因。 - 另外
Update里第二个判断GetFloat(Words) == 1完全没必要,因为如果值已经是1,重新设置为1没有任何意义。
修复方案
移除删除键的逻辑,改用直接设置值的方式来控制状态,同时添加PlayerPrefs.HasKey判断避免默认值干扰:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Scriptname : MonoBehaviour { private string Words; public float ShowPrefs; private void Start() { PlayerPrefs.DeleteKey("C"); Words = this.gameObject.name; // 启动时如果键不存在,初始化值为2 if (!PlayerPrefs.HasKey(Words)) { PlayerPrefs.SetFloat(Words, 2); PlayerPrefs.Save(); } } private void Update() { ShowPrefs = PlayerPrefs.GetFloat(Words); // 移除删除键的逻辑,不需要删除,直接通过值来控制状态 } private void OnTriggerStay(Collider other) { if (other.gameObject.name == Words) { PlayerPrefs.SetFloat(Words, 1); PlayerPrefs.Save(); } else { PlayerPrefs.SetFloat(Words, 2); PlayerPrefs.Save(); } } }
额外建议
- 尽量避免在
Update里频繁调用PlayerPrefs相关方法,读写操作相对耗时,必要时可以用局部变量缓存值。 - 比较浮点数时,建议用
Mathf.Approximately代替直接==,避免浮点数精度问题导致判断失效。
内容的提问来源于stack exchange,提问作者Opman
相关产品推荐
相关产品推荐

