Created
July 3, 2023 23:29
-
-
Save drusepth/28005f6bbca892d1c5cdae7230feecc7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEditor; | |
using UnityEngine; | |
[CustomPropertyDrawer(typeof(SerializableDictionary<,>))] | |
public class SerializableDictionaryDrawer : PropertyDrawer | |
{ | |
private const float Padding = 2f; | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
EditorGUI.BeginProperty(position, label, property); | |
position.height = EditorGUIUtility.singleLineHeight; | |
SerializedProperty keysProperty = property.FindPropertyRelative("keys"); | |
SerializedProperty valuesProperty = property.FindPropertyRelative("values"); | |
int size = keysProperty.arraySize; | |
float halfWidth = (position.width - Padding) * 0.5f; | |
Rect leftRect = new Rect(position.x, position.y, halfWidth, position.height); | |
Rect rightRect = new Rect(position.x + halfWidth + Padding, position.y, halfWidth, position.height); | |
EditorGUI.LabelField(leftRect, "Keys"); | |
EditorGUI.LabelField(rightRect, "Values"); | |
// EditorGUI.indentLevel++; | |
for (int i = 0; i < size; i++) | |
{ | |
Rect keyRect = new Rect(position.x, position.y + (position.height + Padding) * (i + 1), halfWidth, position.height); | |
Rect valueRect = new Rect(position.x + halfWidth + Padding, position.y + (position.height + Padding) * (i + 1), halfWidth, position.height); | |
EditorGUI.PropertyField(keyRect, keysProperty.GetArrayElementAtIndex(i), GUIContent.none); | |
EditorGUI.PropertyField(valueRect, valuesProperty.GetArrayElementAtIndex(i), GUIContent.none, true); | |
} | |
// EditorGUI.indentLevel--; | |
Rect addButtonRect = new Rect(position.x, position.y + (position.height + Padding) * (size + 1), position.width, position.height); | |
if (GUI.Button(addButtonRect, "Add Key-Value Pair")) | |
{ | |
Debug.Log("Adding kv pair"); | |
keysProperty.arraySize++; | |
valuesProperty.arraySize++; | |
} | |
EditorGUI.EndProperty(); | |
} | |
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) | |
{ | |
SerializedProperty keysProperty = property.FindPropertyRelative("keys"); | |
int size = keysProperty.arraySize; | |
return EditorGUIUtility.singleLineHeight * (size + 1) + Padding * size; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment