I'm making a simple evolution clicker game. I want the score to be saved when the game is closed on android.
I have implemented the Brackeys save system . Binaries are created when exiting the game and read when starting the game or at least on paper I want to do that.
This is the code in SaveSystem.cs :
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class SaveSystem
{
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 have the following code:
private void OnApplicationQuit()
{
SaveSystem.SavePlayer(this);
}
And in the same script, I also load the player data:
public void LoadPlayer()
{
playerData data = SaveSystem.LoadPlayer();
score = data.score;
}
The load function is called at start
void Start()
{
spawner = GameObject.Find("enemySpawner");
LoadPlayer();
UpdateScore();
}
This system works perfectly on PC, but when I do the build for android it doesn't save or load the data. I have used persistentDataPath because it is cross-platform when it comes to assigning the address in the file system. Is there an error in the code that I can't catch? or, is this not the correct save system in android?
Thanks in advance.
It's not the method you're using, but it worked perfectly for me when I created my own, also with Unity2D.
This code should save the value of your variable in the PlayerPrefs, to get the value you must do the following.
I am attaching a ready-made script below for you to see how it works.
That little piece of code should give a different value every time you run it, you can check it by "print()".
I hope I've been helpful, although I'm not sure if this answer is going to help you or not.
If you have any questions or it doesn't work for you, feel free to comment on this answer so I can see it.