Tailor
Tailor

Reputation: 303

PlayerPrefs not working on android

I managed to add a score and a highscore counter to my android app. Everything went fine and worked good in Unity. I build my app and wanted to test it on my phone but the highscore counter, which is saved using PlayerPrefs wont show... There are many ways out there but nothing worked :( any ideas ?

Here is my code

 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();
     }
 }

}

Upvotes: 0

Views: 3232

Answers (1)

hanoldaa
hanoldaa

Reputation: 616

You are calling PlayerPrefs.GetString("HighScore") without a default value, so it'll return "" if the highscore hasn't been saved yet. Since you retrieve the highscore before it's ever saved, you are probably hitting a FormatException: Input string was not in a correct format. exception because it's returning "" to the int.Parse() call which is invalid input. You should switch that line to

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

Better yet, store everything as int's and cast the int to a string for text, much safer. Track the Score and HighScore locally so that you don't have to retrieve the highscore from playerprefs every frame!

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();
        }
    }
}

Upvotes: 3

Related Questions