1
\$\begingroup\$

I'm writing a custom editor for my GridModel object. The object has 2 fields; Vector2Int dimensions and a Dictionary<Vector2Int, bool> grid variable. Since the script will mostly be editted in the prefab editor, I save the fields with the serializedObject property. This works fine for the dimensions variable, but the serializedObject.FindProperty("grid") method returns null. My guess is this is because the Dictionary object is not serializable.

My question therefor is, how can I save the Dictionary type in the serializedObject property to make sure the grid field is the same in the prefab editor as in any other editor?

These are my scripts:

public class GridModel : MonoBehaviour, IGridModel
{
    public Dictionary<Vector2Int, bool> grid;
    public Vector2Int dimensions;
}


CustomEditor(typeof(GridModel))]
public class GridModelEditor : Editor
{
    public override void OnInspectorGUI()
    {
        Vector2Int dimensions = EditorGUILayout.Vector2IntField("Size", serializedObject.FindProperty("dimensions").vector2IntValue);
        serializedObject.FindProperty("dimensions").vector2IntValue = dimensions;
        SerializedProperty serializedField = serializedObject.FindProperty("grid"); // Returns null
        serializedObject.ApplyModifiedProperties();
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ You can use the Custom Serialization guide from the manual to serialize your dictionary into a flat array of {Vector2Int, bool} pairs, and deserialize it back to a dictionary on load/change. \$\endgroup\$
    – DMGregory
    Commented Nov 9, 2021 at 19:48

1 Answer 1

2
\$\begingroup\$

I believe you are right, Unity cannot serialize standard dictionaries. I've used this library to serialize Dictionaries in my projects before. The README has a lot of great info features, limitations and usage. In your case, it would be:

public class GridModel : MonoBehaviour, IGridModel
{
    // This class can be defined elsewhere if desired
    [Serializable]
    public class Vec2iBoolDictionary : SerializableDictionary<Vector2Int, bool>;
    
    public Vec2iBoolDictionary grid; // This dictionary should now be serializable
    public Vector2Int dimensions;
}

Since Vec2iBoolDictionary inherits from SerializableDictionary which in turn inherits from Dictionary I don't believe you will have to change any other parts of your code that use the Dictionary. I'm not sure if there are any further steps when writing a custom editor, typically I'll just use the default editor.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .