【问题标题】:Unity C# Player Prefs Highscore not workingUnity C# Player Prefs Highscore 不起作用
【发布时间】:2020-06-17 10:17:25
【问题描述】:

我在统一使用 PlayerPrefs 时遇到错误 (C#) 在安卓上

好像没救了

脚本 1

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scores : MonoBehaviour
{
    public static int highscore;
    public static int points;

    public void Start()
    {

    }

    public void Update()
    {
            highscore = PlayerPrefs.GetInt("highscore");
            PlayerPrefs.SetInt("highscore", highscore);
            PlayerPrefs.Save();
    }
}

脚本 2(使用它的部分)

    void Update()
    {
        highscore = PlayerPrefs.GetInt("Highscore");


        if (points > highscore)
        {
            highscore = points;
            highscoretext.text = "Highscore: " + highscore;
            highscoretext2.text = "Highscore: " + highscore;
        }

当我得到一个高分例如 12 并且我死了我回到主屏幕然后回到游戏并且重新启动应用程序时高分是相同的游戏时,我可以弄清楚

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    当您现在设置高分时,您将获得当前的高分并将其存储在highscore 变量中。然后,您继续使用highscore 变量覆盖高分,有效地将高分设置为自身。你真正想做的是检查当前分数是否超过高分,如果是,则将高分设置为当前分数。

    highscore = PlayerPrefs.GetInt("highscore");
    if(score > highscore)
    {
        PlayerPrefs.SetInt("highscore", score);
        PlayerPrefs.Save();
    }
    

    您的代码不起作用的另一个原因是您在脚本 1 中拼写 "highscore" 时使用了小 h,但在脚本 2 中使用了大 h。

    另外,每次更新都调用PlayerPrefs.GetInt 效率非常低。您应该将它们变成只在需要获取或设置高分时调用的函数。

    【讨论】:

    • 感谢您的帮助,现在可以保存高分但是高分的显示不再起作用了
    • @Roanus 尝试在脚本 2 中去掉 if(score > highscore)highscore = score;。你不需要它,因为你已经在脚本 1 中检查了分数大于高分。编辑:没关系,我没有看到你的第二个回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    相关资源
    最近更新 更多