PlayerPrefs 不适用于 android

PlayerPrefs not working on android

我设法在我的 android 应用程序中添加了分数和高分计数器。一切顺利,在 Unity 中运行良好。我构建了我的应用程序并想在我的 phone 上测试它,但是使用 PlayerPrefs 保存的高分计数器不会显示...有很多方法,但没有任何效果:(有什么想法吗?

这是我的代码

 public class Score : MonoBehaviour {
 public Transform Charakter;
 public Text scoreText;
 public Text HighscoreText;

 public void Start()
 {
     HighscoreText.text = PlayerPrefs.GetString("HighScore");
     PlayerPrefs.Save();
 }

 private void Update()
 {
     scoreText.text = Charakter.position.x.ToString("0");

     int score = int.Parse(scoreText.text);
     int highscore = int.Parse(PlayerPrefs.GetString("HighScore"));

     if (score > highscore)
     {
         PlayerPrefs.SetString("HighScore", scoreText.text);
         PlayerPrefs.Save();
     }
 }

}

您调用的 PlayerPrefs.GetString("HighScore") 没有默认值,因此如果尚未保存最高分,它将 return ""。由于您在高分保存之前检索它,您可能会遇到 FormatException: Input string was not in a correct format. 异常,因为它 returning "" 到 int.Parse() 调用,这是无效输入。您应该将该行切换为

int highscore = int.Parse(PlayerPrefs.GetString("HighScore", "0"));

更好的是,将所有内容存储为 int 并将 int 转换为文本字符串,这样更安全。在本地跟踪 Score 和 HighScore,这样您就不必每帧都从 playerprefs 中检索 highscore!

public class Score : MonoBehaviour
{
    public Transform Charakter;
    public Text scoreText;
    public Text HighscoreText;

    private int Score;
    private int HighScore;

    public void Start()
    {
        HighScore = PlayerPrefs.GetInt("HighScore", 0);
        HighScoreText.text = HighScore.ToString();
    }

    private void Update()
    {
        Score = Mathf.FloorToInt(Charakter.position.x);
        scoreText.text = Score.ToString();

        if (Score > HighScore)
        {
            HighScore = Score;
            HighScoreText.text = HighScore.ToString();
            PlayerPrefs.SetInt("HighScore", HighScore);
            PlayerPrefs.Save();
        }
    }
}