- Home /
Dictionairy Serialization Problem: Keys and values get lost
So, I've been working on this problem for a while. I have an .asset, derived from a Scriptable Object, that is mainly one float and a Dictionairy. I've been using help from here: http://answers.unity3d.com/questions/460727/how-to-serialize-dictionary-with-unity-serializati.html to serialize my Dictionairy. My keys look like this:
[Serializable]
public class Hex : IEquatable<Hex>, ISerializationCallbackReceiver
{
public static Hex[] directions = {
new Hex(+1, 0), new Hex(+1, -1), new Hex( 0, -1),
new Hex(-1, 0), new Hex(-1, +1), new Hex( 0, +1)};
[SerializeField]
public int q;
[SerializeField]
public int r;
public Hex(int q, int r)
{
this.q = q;
this.r = r;
}
public Hex() : this(0,0) { }
//more stuff here
public override bool Equals(System.Object obj)
{
Hex h = obj as Hex;
if (h == null)
return false;
else
return h.q == q && h.r == r;
}
public override int GetHashCode()
{
string s = q + "," + r;
return s.GetHashCode();
}
public bool Equals(Hex other)
{
if (other == null)
return false;
else
return other.q == q && other.r == r;
}
public void OnAfterDeserialize()
{
}
public void OnBeforeSerialize()
{
}
}
I've been working on different solutions, but basically what I am trying to do is:
Have a custom editor window that can Generate, Load and Save those Dictionairy-Assets (They're Grid-Maps). I've been using Object-Fields to get my target, then change it, and "set it Dirty", or generate new Assets and copy and paste, but somehow my Map-Objects lose Keys and Values, causing IndexOutOfRange Errors here and there.
Is the problem in my Key Class?
Unfortunately my code is starting to get messy.
I feel like, if that does not work out I just write my own FileWriter that writes the Dictionairy in a textfile and read it out when I need it. It's exhausting, help!
Here's a picture of what I am trying to do:
I don't see the actual dictionary in your code, so it's hard to diagnose directly, but let me tell you how I solve this problem:
I usually create a secondary serializable struct that hass all of the value data as well as a field for the key. Then in OnBeforeSerialize, I copy the source data into those structs and write them out to an array or list which can be automatically serialized by Unity. Then in OnAfterDeserialize, I read that list or array back into the Dictionary.
It can be a bit troublesome when working in the editor, as serialization happens frequently, but in the game, it works well.