- Home /
Serialize Nested Lists
Will Unity not serialize nested lists such as:
List<List<int>> nList = new List<List<int>>();
How can we serialize this list?
In what way do you want to serialize it? Internally as an asset? Externally as a file or a string?
I need to serialize it as an asset (ScriptableObject) saved in the project directory.
It's not just working like that? I serialize some complicated stuff and it always seems to work on ScriptableObject - what is happening?
List<int> serializes fine. But with List<List<int>>, all data is lost when unity is restarted.
Hmmm - I guess you might have to implement ISerializable then and store the data yourself - perhaps serializing that list of lists into a string or byte array using BinaryFormatter.
Answer by CapnCromulent · Sep 14, 2012 at 04:16 AM
Unfortunately, you'll have to write a wrapper class, like:
[System.Serializable]
public class ListWrapper
{
public List<int> myList;
}
then declare within your ScriptableObject
List<ListWrapper> nList =new List<ListWrapper>();
It works fine but doesn't work if I make the wrapper class a template. Any suggestions for that?
@svizcay you mean something like this?
[System.Serializable]
public class ListWrapper<T>
{
public List<T> myList;
}
You should do that:
[System.Serializable]
public class IntListWrapper : ListWrapper<int> { }
[System.Serializable]
public class FloatListWrapper : ListWrapper<float> { }
And so on for each type.
It works for me. $$anonymous$$y version is 2017.3 ... Thank you so much!
A note in case this helps anyone else: your wrapper class can't inherit from ScriptableObject or $$anonymous$$onoBehaviour, as Unity serializes those differently.
Answer by dzliergaard · Feb 26, 2018 at 09:44 PM
For anyone still coming upon this answer, you could simplify your wrapper class by implementing the bracket accessor, so you can access the elements in the wrapped list the same as you would an actual List.
public int this[int key]
{
get
{
return InnerList[key];
}
set
{
InnerList[key] = value;
}
}
Answer by rajeshranjan531 · Dec 11, 2018 at 05:55 AM
This does not answer the question. Property drawers can't change what data is actually serialized. Nested lists / array simply can't be serialized by Unity and you need to use a wrapper. You just throw a link at us which seems to just provide a property drawer for reorderable lists. This is off topic.