2

Help, PlayerPrefs doesn't seem to work and can't figure out why.

I have a simple game that starts with:

void Start()
{

    if (PlayerPrefs.GetInt("IsReturningUser") == 1)
    {
        ScoreLabel.text = "Welcome back, friend!";
    }
    else
    {
        PlayerPrefs.SetInt("IsReturningUser", 1);
        ScoreLabel.text = "Welcome new player";
    }

When testing on my Android device from Unity Editor (build and run while connected) it works as intended - when I return to app second time it detects I'm returning.

However when I published the same code to Google Play store and clean installed from there, it never detects I'm a returning user when I return to app the second time.

Also strange, while it doesn't work on my Android phone, on my wife's phone installed from the Play Store it does detect as a returning user when she opens it the second time.

Any ideas?

Unity 5.3.6 My phone - Redmi Note 3, Android 6.0.1 MIUI 8.2 Stable Wife phone - OnePlusX

Simon Newstead
  • 395
  • 4
  • 19

2 Answers2

4

I had similar issue before. I solved by adding a PlayerPrefs.Save() after calling the other PlayerPrefs.Set* methods. This forces all writes to disk.

Jer In Chicago
  • 828
  • 5
  • 7
  • Thanks, that solves. I was exiting my phone by force closing which I guess skips the regular saving on exit. Now I save manually using this each time I set the values and that works. – Simon Newstead Aug 15 '17 at 13:24
3

it does detect as a returning user when she opens it the second time

Force it to save. Maybe that's the problem. After calling PlayerPrefs.SetInt("IsReturningUser", 1);, call PlayerPrefs.Save() to save it.


If that does not help at-all, give the PlayerPrefs.GetInt function a default value if the key does not exist like I did here. Just change PlayerPrefs.GetInt("IsReturningUser") == 1 to PlayerPrefs.GetInt("IsReturningUser", 0) == 1.


Finally, if still not working, just use File.WriteAllBytes and save the file to Application.persistentDataPath/yourFolderName. You can find full example here.

Programmer
  • 121,791
  • 22
  • 236
  • 328