using UnityEngine;
using System;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public static class SaveLoadManager {
public static void SavePlayer(Player player)
{ //create binary file
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath+"/player.sav",FileMode.Create);
//this will use the class PlayerData
PlayerData data = new PlayerData(player);
//use Serialize -
bf.Serialize(stream, data);
//close file stream
stream.Close();
}
//load the file
public static int[] LoadPlayer() {
//check the file exist
if (File.Exists(Application.persistentDataPath + "/player.sav"))
{
//open binary file
BinaryFormatter bf = new BinaryFormatter();
FileStream stream = new FileStream(Application.persistentDataPath + "/player.sav", FileMode.Open);
PlayerData data = bf.Deserialize(stream) as PlayerData;
//close file stream
stream.Close();
//return data from file
return data.stats;
}
else {
Debug.LogError("File don't exist!");
return new int[5];
}
}
}
// need to use using System; to use Serializable area.
[Serializable]
public class PlayerData {
// more convenient for us to store data
public int[] stats;
public PlayerData(Player player) {
stats = new int[5];
stats[0] = player.level;
stats[1] = player.energy;
stats[2] = player.health;
stats[3] = player.attack;
stats[4] = player.defense;
}
}