Creating Serializable Dictionary Class

Rather than rewrite the suggested hacks for getting around the unserializability of dictionaries, I’ve been working to write a basic class which implements IDictionary and is serializable. I’ve been using information from other questions and assorted MSDN docs and I’ve gotten a basic structure down that I feel should work. Unfortunately it doesn’t. The below code has been truncated to only what I believe is necessary.

[Serializable]
public struct SKeyValuePair<TKey, TValue>
{
	public TKey   Key   { get; set; }
	public TValue Value { get; set; }

	public SKeyValuePair(TKey key, TValue value)
	{
		Key   = key   ;
		Value = value ;
	}
}

[Serializable]
public class SDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
	[SerializeField]
	private List<SKeyValuePair<TKey, TValue>> dict = new List<SKeyValuePair<TKey, TValue>>();

	#region IDictionary Implementation
	...
	#endregion
}

The SDictionary is then sub-classed with non-generic parameters (as suggested here):

[Serializable]
public class SDictTest : SDictionary<string, string> {}

And finally used in a MonoBehavior like so (with added editor for usability, omitted here to shorten post length):

public class SDictMono : MonoBehaviour
{
	public SDictTest sdt = new SDictTest();
}

Now I can add entries to my dictionary:

35131-sdict2.png

But despite this and all of my careful serializing, it still disappears on play:

35132-sdict1.png

What’s up with that? I’m mildly suspicious of my use of a List with a Serializable, but generically typed SKeyValuePair in SDictionary, but can’t say for sure that that’s it.

Nice thing abotu scriptable objects is you can use them as a field in your monobehaiour and they just work :slight_smile:

Having said that, I share your pain on this issue. Getting custom data structures with custom editors to properly save properly can be a pain. I’ve been through it, but it was awhile back so, outside of googling advice on ScriptableObjects and Custom Editors, i don’t know how much else I can offer. :frowning:

edit:

Actually, as I recall, one of the things that tripped me up is that what Unity can serialize is actually quite limited.
The list is here:

It may very well not be able to serialize generic types at all. There are certainly types you could pass for them that it could not serialize.