PlayerPrefs not saving after game fully closes or in Unity Editor (Android)

Hello,

I know that this has been an over-posted issue, but I’ve looked across Unity’s website and I cannot find a solution. I’m starting to wonder if this is a bug.

My PlayerPrefs aren’t saving in the Unity Editor or my Android Phone. They save until I close the game and then they reset.

Here’s my code:

//Inside a function that gets called on the game end
if (score >= highScore) {
                highScore = score;
                PlayerPrefs.SetInt ("High Score", highScore);
                PlayerPrefs.Save ();
                GameObject.Find ("Final Score").GetComponent<Text> ().color = Color.red;
            }

//Gets called inside of Start function
if (PlayerPrefs.HasKey("High Score")) {
            highScore = PlayerPrefs.GetInt ("High Score");
        } else {
            highScore = 0;
        }

highScoreTextResults.text = "High Score: " + PlayerPrefs.GetInt ("High Score");
highScoreTextPause.text = "High Score: " + PlayerPrefs.GetInt ("High Score");
highScoreTextStart.text = "High Score: " + PlayerPrefs.GetInt ("High Score");

I can post more code if necessary.

I’m running Unity 5.3.1f1 on a Windows 10 device, using a Samsung Galaxy S2 Android phone running Android 4.2 Jellybean.

Thanks for your help.

Um… Do you run as administrator? PlayerPrefs on windows are stored in registry and you might not have access. Not sure about Android.

Or maybe score is never >= highScore?

Do you have company name and product name filled in editor?

I can, but I don’t specifically run as an administrator when opening Unity. I’ve opened the PlayerPrefs on Windows before, so I know how to access them. My issue is occurs on my Android build also so I believe the issue is in my code.

highScore is set inside this if statement, and if it doesn’t exist at the start of the game, it gets set to zero. Since the score variable at the start of every game is zero, this if statement always returns true at least once. The above code works normally. It just resets every time I re-open the game so the issue is in the saving.

Yes, why?

Thanks again.

There’s one rare case caused by them remembering those variables in /[CompanyName]/[ProductName]/ registry key on windows or com.CompanyName.ProductName on android and if they’re empty…

Oh, right, are you perhaps PlayerPrefs.SetInt(…) in Start() or such so that it resets each start?
You can try to check if registry key is actually there and has value. Where it’s stored is described in PlayerPrefs manual.
If not then I’m out of ideas (only remaining one is it’s bug)

I found my registry for my PlayerPrefs on Windows as an RG_DWORD.

Oddly enough, it worked when I changed PlayerPrefs.SetInt() to PlayerPrefs.SetFloat().

I have no idea why it wasn’t working, but I’m glad I got it fixed.