- Home /
PlayerPrefs not Saving Properly on Android (Works in Editor) - OnApplicationPause/Quit
I'm currently developing a mobile game for Android and have run in to an annoying problem.
I'm using PlayerPrefs to save various game state variables and in the editor this works and runs fine regardless of whether it's done via a save button, OnApplicationPause or OnApplicationQuit. However, when I build the .apk and put it on my tablet for testing, the Save call in OnApplicationPause and/or Quit never seem to run, so when I tap the home button and close the app the data is not saved. The issue isn't with the Save method itself, because I set up a temporary button to run the Save method and if I use that before closing the app the data is all correctly saved.
I was wondering if anyone had experienced anything similar and had any idea as to how I can force OnApplicationPause/Quit to happen or for the app not to close when swiped away until the Save method has finished?
Save method:
public void SaveData()
{
PlayerPrefs.SetInt("credits", credits);
PlayerPrefs.SetInt("crystal", crystal);
PlayerPrefs.SetInt("dust", dust);
PlayerPrefs.SetInt("lumber", lumber);
PlayerPrefs.SetInt("metal", metal);
PlayerPrefs.SetInt("quantum", quantum);
PlayerPrefs.SetInt("cRegCap", currentRegDailyCap);
PlayerPrefs.SetInt("cQCap", currentQuantumDailyCap);
PlayerPrefs.SetInt("regCap", regDailyCap);
PlayerPrefs.SetInt("qCap", quantumDailyCap);
PlayerPrefs.SetInt("regTick", regularTickAmount);
PlayerPrefs.SetInt("qTick", quantumTickAmount);
PlayerPrefs.SetString("timeClosed", System.DateTime.UtcNow.ToBinary().ToString());
PlayerPrefsX.SetIntArray("packs", packs);
PlayerPrefsX.SetBoolArray("cards", cards);
PlayerPrefsX.SetIntArray("collectors", collectors);
PlayerPrefs.Save();
}
OnApplicationPause/Quit:
void OnApplicationPause(bool pauseStatus)
{
paused = pauseStatus;
}
void OnApplicationQuit()
{
SaveData();
}
void Update()
{
if(paused)
{
SaveData();
}
}
Answer by phil_me_up · Mar 11, 2016 at 12:03 AM
The first thing I'd suggest is to call SaveData() from within OnApplicationPause and not wait for the next Update call (which may not happen).
void OnApplicationPause(bool pauseStatus)
{
if(pauseStatus)
SaveData();
}
Ah, this is working, thank you! I had what you have there previously, but without the bool pauseStatus and the if statement and it wasn't working, so I had ruled out doing it this way. Thanks again.
Your answer
Follow this Question
Related Questions
Loading a save/playerprefs from a different game? 2 Answers
PlayerPrefs don't load again after Android game closes for the first time. 1 Answer
Playerprefs not working on android 0 Answers
Android/IOS: Sharing save file between free and paid versions 0 Answers
How to run Android service behind UnityPlayerActivity? 0 Answers