Save and Load with binary files in Android
Im making a simple Evolution Clicker game for android and i want to mantain the score of the player when the app closes.
Well I implemented the save system from Brackeys.
This is the code i have in the SaveSystem.cs file:
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem //Una clase estática no puede instanciarse
{
public static void SavePlayer(playerController player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Path.Combine(Application.persistentDataPath + "/player.dat");
FileStream stream = new FileStream(path, FileMode.Create);
playerData data = new playerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static playerData LoadPlayer()
{
string path = Path.Combine(Application.persistentDataPath + "/player.dat");
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
playerData data = formatter.Deserialize(stream) as playerData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in " + path);
return null;
}
}
}
In my PlayerController script i save the data when the game quits:
private void OnApplicationQuit()
{
SaveSystem.SavePlayer(this);
}
And I Load the data with this fuction(also in my playerController script)
public void LoadPlayer()
{
playerData data = SaveSystem.LoadPlayer();
score = data.score;
}
I call it in the Start:
void Start()
{
spawner = GameObject.Find("enemySpawner");
LoadPlayer();
UpdateScore();
}
The save system works perfectly fine in the edit mode in PC, but when i build for android the score doesnt save. Any Idea?
Thank you in advance.
Comment
Did you ever figure this out? I have the exact problem.
Try to replace OnApplicationQuit with OnDestroy. It's said here that OnApplicationQuit may not be called in some cases on Android.