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

PlayerPrefs保存分数异常始终为0,求可行解决办法?

PlayerPrefs保存分数始终为0的排查方案
  • 生命周期方法大小写错误
    Unity的启动生命周期方法要求首字母大写的Start(),你写的小写start()不会被Unity自动触发,导致加载分数的逻辑完全没执行,score_system.score一直是默认的0值。修正代码:

    public void Start()
    {
        score_system.score = PlayerPrefs.GetInt("Score");
    }
    
  • score_system引用未初始化
    检查score_system是否在Inspector面板中正确赋值,或者是否在代码里通过FindObjectOfType<ScoreSystem>()等方式完成初始化。如果引用为空,访问score_system.score会返回默认的0,甚至触发空引用异常。

  • score变量未正确更新
    确认游戏运行过程中score_system.score是否被正确修改(比如得分时累加)。可以在保存前先打印当前分数,验证数值是否正确:

    public void SaveButtonClick(){
        Debug.Log("当前待保存分数:" + score_system.score);
        PlayerPrefs.SetInt("Score", score_system.score);
        PlayerPrefs.Save();
        print(PlayerPrefs.GetInt("Score"));
    }
    

内容的提问来源于stack exchange,提问作者NietTeDoen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:41:07