Question by
MattDahEpic · Apr 30, 2016 at 01:54 AM ·
jsonfile-io
JsonUtility not making JSONs
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.
Comment
Best Answer
Answer by MattDahEpic · May 01, 2016 at 08:41 PM
Changing the fields from getter/setters to be values allowed the json to be exported.
Your answer
Follow this Question
Related Questions
Can I create text files on Linux? 1 Answer
Store game objects in a JRPG game 0 Answers
.json to a sprite 0 Answers
JSON parse error 0 Answers
Reading an array from a JSON Error 1 Answer