I have some code that’s supposed to save the game state to disk when the game closes, but it isn’t really working. The file is created when the game exits with the contents of {}
which doesn’t have any of the fields nor values of the object that was supposed to be JSON’d.
Code:
using UnityEngine;
using System.IO;
[System.Serializable]
public class GameStateConstants : MonoBehaviour {
public int slotsUnlocked { get; set; }
public int daysComplete { get; set; }
[System.NonSerialized] private static readonly FileInfo gameSave = new FileInfo(Application.persistentDataPath+Path.DirectorySeparatorChar+"save.sav");
public static GameStateConstants instance;
void Awake () { DontDestroyOnLoad(this); }
void Start () {
if (instance == null) instance = this;
//set defaults in case of new save
instance.slotsUnlocked = 1;
instance.daysComplete = 0;
//overwrite values from saved data
if (gameSave.Exists) {
using (StreamReader input = gameSave.OpenText()) {
JsonUtility.FromJsonOverwrite(input.ReadLine(), instance);
}
}
}
void OnApplicationQuit () {
//save to disk
if (!gameSave.Exists) gameSave.CreateText().Close();
using (StreamWriter output = new StreamWriter(gameSave.FullName,false)) {
output.WriteLine(JsonUtility.ToJson(instance));
}
}
}
Any help is appreciated, thanks.