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