You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:50:25