Serializable Data In C#

(Game.cs)

//In this script you can easily add variables like, bool, int, and even floats.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

[System.Serializable]

public class Game

{

public static Game current = new Game();

public int _myInt;

public float _myFloat;

public bool _myBool;

}

(SaveLoad.cs)

//This script is what does all your serialization and de-serialization! Just change the _myInt, etc , to your own variables. Remember, you cannot save GameObjects themselves, rather you save their positions with vectors and transforms.

using UnityEngine;

using System.Runtime.Serialization.Formatters.Binary;

using System.IO;

public static class SaveLoad

{

public static void SaveGame()

{

BinaryFormatter bf = new BinaryFormatter();

if (File.Exists(Application.persistentDataPath + "/SaveGame.dat"))

{

FileStream file = File.Open(Application.persistentDataPath + "/SaveGame.dat", FileMode.Open);

Game game = new Game();

game._myInt = Game.current._myInt;

game._mybool = Game.current._myBool;

game.myFloat = Game.current._myFloat;

bf.Serialize(file, Game.current);

file.Close();

}

else

{

FileStream file = File.Create(Application.persistentDataPath + "/SaveGame.dat");

Game game = new Game();

game._myInt = Game.current._myInt;

game._mybool = Game.current._myBool;

game.myFloat = Game.current._myFloat;

bf.Serialize(file, Game.current);

}

}

public static void LoadGame()

{

if (File.Exists(Application.persistentDataPath + "/SaveGame.dat"))

{

BinaryFormatter bf = new BinaryFormatter();

FileStream file = File.Open(Application.persistentDataPath + "/SaveGame.dat", FileMode.Open);

Game game = (Game)bf.Deserialize(file);

file.Close();

Game.current._myInt = game._myInt;

Game.current._myBool = game._mybool;

Game.current._myFloat = game.myFloat;

}

else

{

Debug.Log("File Does Not Exist");

}

}

}

When you want to load the file, usually on Awake(), simply add.. SaveLoad.LoadGame();

And when you want to save, usually on game over, simply add.. SaveLoad.SaveGame();

Thats it!!