PlayerPrefs没有在android上工作

【PlayerPrefs没有在android上工作】人生处万类,知识最为贤。这篇文章主要讲述PlayerPrefs没有在android上工作相关的知识,希望能为你提供帮助。
我设法为我的android应用程序添加了一个分数和一个高分计数器。一切顺利,在Unity中运作良好。我构建我的应用程序,并希望在我的手机上测试它,但高分计数器,使用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"),所以如果尚未保存高分,它将返回""。由于您在保存之前检索了高分,因此您可能会遇到FormatException: Input string was not in a correct format.异常,因为它返回到无效输入的int.Parse()调用。您应该将该行切换为
int highscore = int.Parse(PlayerPrefs.GetString("HighScore", "0"));

更好的是,将所有内容存储为int,并将int转换为文本字符串,更安全。在本地跟踪得分和HighScore,这样您就不必每帧都从playerprefs中获取高分!
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(); } } }


    推荐阅读