jsonUtlility save/load ScriptableObjects
I'm currently working on a small project, this project contains one script with a template for Scriptable objects that contains 2 integers (questNumber and questStatus) I have created 5 objects from this template called quest1 - 5.
and a SaveLoad Script which uses the ToJson and FromJsonOverwrite methods (the content of these methods has been changing a lot as i have been trying all the other threads on this site)
I would like to save the Players progress using JsonUtility or any other method as I have been struggling to do this (I'm very new to serialization and games save/loads) and was hoping someone could give me a hand (I have been trying to crack this for 4 days now).
The plan I have is to save and load the state of all the Quest objects at runtime.
Thanks :)
Ok so I have some more information in case it will help:
$$anonymous$$y save function is returning ' {}' in the json file, the code is:
public static void Save()
{
var instance = Resources.LoadAll<Job$$anonymous$$anager>("");
string data = JsonUtility.ToJson(instance);
File.WriteAllText(Application.persistentDataPath + "/save.txt", data);
}
I have all the objects created from the scriptableObject Named Job$$anonymous$$anager, however nothing is saved.
It would be of great help if you could show the code for your Job$$anonymous$$anager. Some important things to remember, your class ($$anonymous$$onoBehaviour/ScriptableObject derived or plain class) should be marked with the serializable attribute. $$anonymous$$ake sure all the fields you want serialized are public and remember that the types supported are only those that Unity already serializes by default, so stuff like dictionaries or bidimensional arrays won't work.
Hi $$anonymous$$acDx
Please see below the job manager: using System.Collections; using System.Collections.Generic; using UnityEngine;
[CreateAsset$$anonymous$$enu(fileName = "Job", menuName = "Jobs")]
[Serializable]
public class Job$$anonymous$$anager : ScriptableObject {
public int questNumber;
public int questStatus;
[NonSerialized]
public bool created = false;
void Awake()
{
if (!created)
{
DontDestroyOnLoad(this);
created = true;
}
}
}
I think i have serialized it correctly.
Thanks
Answer by MacDx · May 08, 2018 at 03:54 PM
@Tsucasa your JobManager class seems correct to me. The most likely thing to go wrong there then, is the loading of the JobManager object. Are you sure the instance variable isn't null when passing it to the ToJson method, put some logs there or debug with breakpoints so you can better know. Also instead of using LoadAll try using Load with the appropriate path.
Like this:
//Assuming your file is named JobManager too and it is placed right below the resources folder
var instance = Resources.Load<JobManager>("JobManager");
I tried that and it worked as expected. Hope this helps!
Hi $$anonymous$$acDX
Here's a Screenshot of the 5 Objects created from the Job$$anonymous$$anager Script.
would var instance = Resources.LoadAll<jobmanager>("Jobs");
work?
Thanks
Hi $$anonymous$$acDx
I have tried var instance = Resources.LoadAll<jobmanager>("Jobs");
however when I debug.log it I just get jobmanager[] which if I then debug.log instance[0] I see job1. would a load work with that?
I tried this: foreach (var i in instance) { data += JsonUtility.ToJson(i); }
but the above doesn't create a valid Json file. ( see attached file)
Also please note i'm in the process of rena$$anonymous$$g Quest to Job hence why they say JobNumber and JobStatus rather than questNumber/Status as before.
Thanks
[1]: /storage/temp/116524-save.txt
Assu$$anonymous$$g the data variable you're showing is an empty string, yeah that for loop will never work. ToJson returns a Json string that's supposed to be only one file but you are putting them all together then try to read them as a single file and that will not work
//Your file would contain something like this
{}{}{}{} //Invalid Json
Json files can only contain 1 root object (which can be an array), and values (being array elements or object properties) are always separated by commas, so yeah by mashing up multiple valid Json strings, output by the ToJson method, you are making a NON valid Json.
To make that code work you'll need to modify it a little bit like this:
data = "[";
for(int i = 0; i < instance.Length ; i++)
{
data += JsonUtility.ToJson(instance[i]);
//Add a comma after every element except for the last one
if( i < instance.Lenght - 1) data += ",";
}
data += "]";
//Then write data to a file with data looking like this
// [{},{},{}] VALID JSON
Hi $$anonymous$$acDx
Thanks the above did create a Valid Json file, Please can you confirm how I should load this data though? I can't think of how to assign each entry in the file to an instance of Job$$anonymous$$anager.
I was Currently using :
if (FileCheck())
{
var instance = Resources.LoadAll<Job$$anonymous$$anager>("Jobs");
var data = File.ReadAllText(Application.persistentDataPath + "/save.txt");
JsonUtility.FromJsonOverwrite(data, instance);
}
else
{
Debug.LogError("Save file not found");
}
However i believe that tries to over write one object with all the data?
Hi $$anonymous$$acDx
Apologies for the lack of info, Basically when the save function is called it only seems to save the InsanceIds please see attached save.txt file.
when I do a Debug.Log, if I type just wrap I just get a Job$$anonymous$$anagerWrapper object, if I type wrap.array then I get Job$$anonymous$$anager[], if I type wrap.array[0] then I get Job1[job$$anonymous$$anager]
Please see attached screenshots for breakpoints results from the save.alt text (have to put the 2nd in a separate post as it wont allow me to add anymore attachments).
On Loading its passed all the instanceIDs that are in the save.txt, when I do a Debug.Log(j.array[0].jobStatus)) it's set to 0 and it should be 1 as in the save before that's what it was set to.
I hope this is enough info if there's anything else that may help you please let me know
Thanks
Here's screenshot 2
Also I just noticed if I Debug.Log(jsonData); in the Load function i get the same json data 5 times, see result3.png
[1]: /storage/temp/116798-result3.png
I see. I wish to continue to help you but this is getting too long and it's a separate issue since saving/loading jsons is already working for you. The original question in this post has already been solved, so please ask a separate question.
Regards