- Home /
ScriptableObject List doesn't save
Edit: So I have found out that EditorUtility.SetDirty() is obsolete. How do I save it then?
I am making a Item database, inspired by BurgZerg, and for some reason, my list in the Database doesn't save after unity reload or it erases all data after I save a the ItemDatabase.cs even tho I have EditorUtility.SetDirty() after every change.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;
public class ItemDatabase : ScriptableObject {
[SerializeField]
List<Item> items = new List<Item> ();
public void Remove(Item item) {
items.Remove (item);
EditorUtility.SetDirty(this);
}
public void RemoveAt(int index) {
items.RemoveAt (index);
EditorUtility.SetDirty(this);
}
public void Add(Item item) {
items.Add (item);
EditorUtility.SetDirty(this);
}
public int CountItems() {
return (int)items.Count;
}
public Item Item(int index) {
return items.ElementAt (index);
}
}
Answer by FlightOfOne · Nov 06, 2017 at 09:36 PM
Take a look here: https://answers.unity.com/questions/831285/can-you-use-a-serializedobject-to-save-game-state.html
Take a look at all the answers there, maybe one will give you a clue.
The link says I should serialize the List, but it doesn't explain how should I do that. I'm very new to serialization, so still kinda stuck.
Ok, I got it to work now, just had to google more about Serialization. What fixed the problem was that I just made my Item class [System.Serializable]. Also, all variables in the Item class had to be made to [SerializeField].
I think it depends on what what method you use to serialize (xml, json, binary formatter etc..). Some allow allow private fields, and some only allow, public, non properties. But from my experience, almost all of them work if it's public field.
I use scriptable objects a lot but I have never really used them for saving data. I always use xml/jason/binary. i think it's worth exploring Json and X$$anonymous$$L. I think it would be a good investment. It's not that difficult really.
public void SaveJsonData(T _data, string _fullPath)
{
string _json= JsonUtility.ToJson(_data);
File.WriteAllText(_fullPath, _json);
Debug.Log("<color=black>-Json- File Saved to: [" + _fullPath+"]</color>");
}
public T LoadJsonData(string _fileName, string _ext = ".cfg", string _path = "")
{
if (_path == "")
{
_path = Application.persistentDataPath + "/";
}
_path = _path + _fileName + _ext;
if (!File.Exists(_path))
{
Debug.LogError("Not Found: [" + _path + _fileName + _ext + "]");
return default(T); //returns a null for reference type and 0 for values
}
T _deserializedData = JsonUtility.FromJson<T>(File.ReadAllText(_path));
Debug.Log("-Json- File Loaded: " + _path + _fileName + _ext);
return _deserializedData;
}