SetDirty won't work on Nested List
Hi, usually I find my answer by myself but this time - after spending two days on this problem - I give up ^^
So I try to save a List<List<string>>
into a ScriptableObject
but each time I make a change on it and restart Unity changes are lost/reset.
I've already did it with a List<string>
and it worked perfectly, but this nested class got me.
So here's the code:
- MyScriptableObject.cs
using UnityEngine;
using System.Collections.Generic;
public class MyScriptableObject : ScriptableObject {
[System.Serializable]
public class StringList: List<string> { }
[System.Serializable]
public class Container : List<StringList> { }
[SerializeField]
private Container cont;
public void Fill () {
// Fill with some random datas
cont.Add(new StringList { "1A", "1B", "1C" });
cont.Add(new StringList { "2A", "2B", "2C" });
cont.Add(new StringList { "3A", "3B", "3C" });
}
}
- MyCustomEditor.cs
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MyScriptableObject))]
public class MyCustomEditor : Editor {
private MyScriptableObject script;
void OnEnable () {
script = target as MyScriptableObject;
}
public override void OnInspectorGUI () {
DrawDefaultInspector();
if (GUILayout.Button("Fill")) {
script.Fill();
EditorUtility.SetDirty(script);
}
}
}
Since I use EditorUtility.SetDirty(script);
each time I change the asset I would have thought changes were saved but nothing.
Note: When opening the .asset file after a change was made ( Fill()
+ SetDirty()
+ File > Save Project) I notice it doesn't contain my random datas.
So basically changes are not saved into the .asset (i.e SetDirty()
doesn't work) but the inspector keeps track of it until Unity restart (i.e Serialization works).
Any idea how to figure this out?
Answer by ThomLaurent · Sep 15, 2016 at 12:04 AM
I finally found my answer by myself ^^
The Problem
Unity doesn't support inheritance for serialization.
Since I saw my script's list items within the inspector in debug mode (only) I supposed serialization was done correctly but it was not.
The Solution
A wrapper: a class containing the nested List<string>
:
MyScriptableObject.cs
using UnityEngine;
using System.Collections.Generic;
public class MyScriptableObject : ScriptableObject {
[System.Serializable]
public class StringList{
public List<string> list = new List<string>();
}
[SerializeField]
private List<StringList> cont = new List<StringList>();
public void Fill () {
StringList stringList = new StringList();
stringList.list.AddRange(new string[] { "1A", "1B", "1C" });
cont.Add(stringList);
}
}
(MyCustomEditor.cs uses the same script as in the question.)
Note
EditorUtility.SetDirty()
works as intended: it saves the asset (non-scene object) without any Undo management.
Actually it effectively saves your asset at Unity close, since no scene is involved you won't see an asterisk in your Unity window caption.