PS:
Here's my GameState file:
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[System.Serializable]
public class GameStateData
{
public Dictionary<int, Dictionary<int, float>> levelProgress;
public GameStateData(GameState gameState)
{
levelProgress = gameState.levelProgress;
}
}
public class GameState : Singleton<GameState>
{
// Prevent non-singleton constructor use
protected GameState() { }
// declare variables
public Dictionary<int, Dictionary<int, float>> levelProgress = new Dictionary<int, Dictionary<int, float>>();
#region Load / Save Methods
public void LoadGame()
{
string path = Path.Combine(Application.persistentDataPath, "game.save");
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
GameStateData data = formatter.Deserialize(stream) as GameStateData;
stream.Close();
// overwrite current data with loaded data
levelProgress = data.levelProgress;
}
}
public void SaveGame()
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Path.Combine(Application.persistentDataPath, "game.save");
FileStream stream = new FileStream(path, FileMode.Create);
GameStateData data = new GameStateData(this);
formatter.Serialize(stream, data);
stream.Close();
}
#endregion
public void UpdateLevelProgress(int levelPackId, int levelId, float time)
{
if (!levelProgress.ContainsKey(levelPackId))
{
levelProgress.Add(levelPackId, new Dictionary<int, float>());
}
// set time
levelProgress[levelPackId][levelId] = time;
// save to file
SaveGame();
}
}
```