- Home /
Adding more than one item to the list and saving it into JSON file problem
Hello everyone, I want to add an item to the list when the my two gameobject is destroyed and saving it into a JSON file. The problem is, when I look at the json file, it only saves the last gameobject(last item from the list). I've been debugging it for 3 hours and I have no idea where's the problem...
SaveManager
public static void Save(SaveData saveData)
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string json = JsonUtility.ToJson(saveData);
File.AppendAllText(directory + filename, json);
}
public static SaveData Load()
{
fullPath = directory + filename;
SaveData saveData = new SaveData();
if (File.Exists(fullPath))
{
string json = File.ReadAllText(fullPath);
saveData = JsonUtility.FromJson<SaveData>(json);
}
return saveData;
}
GameObject
private void OnDestroy()
{
SaveData saveData = new SaveData();
saveData.scrollViews.Add(scrollView);
SaveLoad.Save(saveData);
}
Answer by xxmariofer · Jan 24 at 11:38 AM
you are creating a new saveData everytime OnDestroy is destroyed, save data should pesist even if the object gets destroyed
public static SaveData saveData;
public static void Save()
{
if(saveData == null) saveData = new SaveData();
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string json = JsonUtility.ToJson(saveData);
File.AppendAllText(directory + filename, json);
}
public static SaveData Load()
{
fullPath = directory + filename;
saveData = new SaveData();
if (File.Exists(fullPath))
{
string json = File.ReadAllText(fullPath);
saveData = JsonUtility.FromJson<SaveData>(json);
}
return saveData;
}
private void OnDestroy()
{
SaveLoad.saveData.scrollViews.Add(scrollView);
SaveLoad.Save();
}
private void OnDestroy()
{
**SaveLoad.saveData.scrollViews.Add(scrollView);**
SaveLoad.Save();
}
But this approach throws an error since I am adding an item to the list when it is not being initialized.
oh I get it now, so I should instantiate saveData only once. I achieved it by instantiating saveData inside my ReferenceManager awake method . Thanks a lot!
Your answer
Follow this Question
Related Questions
Grab a specific item from a list 3 Answers
Instantiate a prefab from jsonarray? 1 Answer
Why the List in the class when using it is not the same in another class ? 1 Answer
New constructor help needed for JSON keyvalue pair 0 Answers
How to compare a string in a list with a gameobject.name from another list of gameobjects 1 Answer