PlayerPrefs highscore works in Unity but not in built game

Hi,

I added a high score script to my game which saves the score like this:

    void StoreLocalHighscore() {

        currentHighscore = PlayerPrefs.GetInt("localhighscore", 0);

        if (currentScore > currentHighscore) {

            PlayerPrefs.SetInt("localhighscore", currentScore);

        }

        PlayerPrefs.Save();

    }

It works fine when I just press play in Unity and try it, but when I create a PC or Android build it doesn’t work.

Do you have any ideas why it isn’t working in the built versions and how could I fix it?

Thanks.

The script itself seems fine, so there would appear to be other issues. You’ll need to give more info. Another suggestion is use https://www.assetstore.unity3d.com/en/#!/content/12047 Log viewer in builds to see debug, prints, or errors that normally may print to your console. This will help determine what may be going wrong.

I have the currentScore variable in the game which works fine in all environments, it counts the player’s score.

I added the StoreLocalHighscore function that should add the currentScore to the currentHighscore if it’s larger than the current one.

The StoreLocalHighscore function is called by an Update function each frame.

When I press play in Unity it counts the high score fine, even if I stop the game and press play again, it stores the highscore as it should be.

But when I build the game for PC or for Android and I test it, the currentHighScore value is always 0. It doesn’t change at all.

Is there anything else that could be relevant?

Is there a build setting maybe that could cause this?

How could I test what might be wrong?

Thanks.

Personally I don’t suggest calling this method in update. If you have a common point where you determine what highscore should be, that’s a better option. Now, that being said, I would say use the asset I linked you. This will help you by letting you see console stuff during the game. You can add debug.log and see what values are showing up while in game.

There are no build settings I’m aware of that would change playerprefs. I have never had issues with playerprefs. There is possibly something overwriting your save value that doesn’t trigger in editor.

If you use that asset I linked, I would do a PlayerPrefs.HasKey check and print out if it’s returning true or not to see if they key is even being created. Then you should also print out the scores to see that they are being set correctly once built out.