hi,
i’ve come to a point where i need to switch from a list to dictionnary in a project, i spent a day doing the code conversion only to know at the end that dictionnaries does not save its values in editor mode, it gets wipped and not serialized whenever i play the game or make a change in code,
is there any sollution for this ?
There’s a few… google up for how to serialize a dictionary in Unity. If I recall it was a custom class that stored the keys as one list and the values as another, and then you accessed it as a Dictionary, but it serialized as a pair of lists? Not sure how viable it was to use, but it seemed relevant.
Here’s a startpoint: https://answers.unity.com/questions/460727/how-to-serialize-dictionary-with-unity-serializati.html
Not sure if that was the one I saw before however… I think it was based on how it breaks them into lists before and after serialization.
Unity’s own documentation for ISerializationCallbackReceiver uses Dictionary as their example:
Though I would argue it’s not the cleanest since it leaves the lists public and open for modification.
Personally I like to encapsulate the data portion so they can’t be easily broken… something like this:
public class zTest02 : MonoBehaviour, ISerializationCallbackReceiver
{
public Dictionary<string, int> MyDict = new Dictionary<string, int>();
[SerializeField]
[HideInInspector]
private DictData[] _dictData;
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
MyDict.Clear();
foreach(var v in _dictData)
{
MyDict.Add(v.Key, v.Value);
}
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
_dictData = new DictData[MyDict.Count];
int i = 0;
foreach(var pair in MyDict)
{
_dictData[i] = new DictData() { Key = pair.Key, Value = pair.Value };
i++;
}
}
[System.Serializable]
private struct DictData
{
public string Key;
public int Value;
}
}
If you wanted the ability to modify the dict through the inspector… well then you’re going to get into a custom editor.
@Kurt-Dekker @lordofduct thanks for your help,
i managed to get it to work , this saved my life thanx again