Hi!
So I’ve managed to make a Binary save system from Brackeys youtube video, I have it so that it saves my players position and number of hearts.
public static void SavePlayer (PlayerStats player)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/player.dat";
FileStream stream = new FileStream(path, FileMode.Create);
PlayerData data = new PlayerData(player);
formatter.Serialize(stream, data);
stream.Close();
}
public static int[] LoadPlayer()
{
if (File.Exists(Application.persistentDataPath + "/player.dat"))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.dat", FileMode.Open);
PlayerData data = formatter.Deserialize(stream) as PlayerData;
stream.Close();
return data.stats;
}
else
{
Debug.LogError("File does not exist.");
return new int[4];
}
}
[System.Serializable]
public class PlayerData
{
public int[] stats;
public float[] position;
public PlayerData(PlayerStats player)
{
stats = new int[4];
stats[0] = player.level;
stats[1] = player.numOfHearts;
stats[2] = player.attack;
stats[3] = player.defence;
position = new float[3];
position[0] = player.transform.position.x;
position[1] = player.transform.position.y;
position[2] = player.transform.position.z;
}
}
I then found a solution through some searching, how to delete the saved file, like a Clear Save in the main menu…
public static int[] DeletePlayerStats()
{
string path = Application.persistentDataPath + "/player.dat";
if (File.Exists(path))
{
File.Delete(path);
return null;
}
else
{
return null;
}
}
The problem with this and I don’t know if I’ve made any errors… Is that the saved file gets deleted which I’m happy about, but my player doesn’t spawn with my default values.(Not even sure if ive set any default values, if so where?) I want the player to spawn back to the beginning of my game, and spawn with 3 hearts. In the PlayerStats script, it even says "public int numOfHearts = 3; and I tried setting it in the Start method aswell, but that would just make my player always spawn with 3 hearts, even if I got 4 and saved.
I can’t figure this out, and I’ve tried alot of ways but it always ends up with my player spawning with 0 hearts and plays the death animation. (Im a beginner so might be an easy solution that i cant solve)
I tried writing return new int[4]; instead of return null; in DeletePlayerStats, but that also doesn’t work, at this point I don’t even know what I’m doing.