Let's say you've got a set of variables that stand for your save game entity. You can, for example, create a class within your save manager script like this:
[Serializable]
public class GameSave {
public DateTime lastMod { get; set; }
public int games { get; set; }
public int coins { get; set; }
public int bestScore { get; set; }
}
Don't forget the [Serializable]
attribute. Then you can write a couple of methods that helps you handle the loading/saving logic, as follow:
public void SaveGame(GameSave gameSave) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/save_game.dat");
bf.Serialize(file, gameSave);
file.Close();
}
public GameSave LoadGame() {
if (File.Exists(Application.persistentDataPath + "/save_game.dat")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/save_game.dat", FileMode.Open);
GameSave gameSave = (GameSave) bf.Deserialize(file);
file.Close();
return gameSave;
} else {
Debug.Log(string.Format("File doesn't exist at path: {0}{1}", Application.persistentDataPath, "/save_game.dat"));
return null;
}
}
Consider also that in this way your save game data will be easily accessible from malicious users who want to hack your game. A much better approach involves an encryption/decryption logic. You can, as a simple example, save your SaveGame object as a json string and than encrypt+save into a file. Anyway, the only way to implement a robust encryption logic is through a client-server handling of encryption keys.