Files
trail-into-darkness/Packages/com.jovian.inspector-tools/Editor/Attributes/CompactDrawerAttribute.cs
2026-04-02 07:22:33 +02:00

79 lines
3.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using System.Text;
using UnityEditor;
#endif
namespace Jovian.InspectorTools {
public class CompactDrawerAttribute : PropertyAttribute { }
}
#if UNITY_EDITOR
namespace Jovian.InspectorTools.Internal {
[CustomPropertyDrawer(typeof(CompactDrawerAttribute))]
public class CompactDrawerAttributeDrawer : PropertyDrawer {
private static readonly List<SerializedProperty> cacheProperties = new();
private static readonly StringBuilder stringBuilder = new();
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) {
return EditorGUIUtility.singleLineHeight;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
cacheProperties.Clear();
stringBuilder.Clear();
EditorGUI.BeginProperty(position, label, property);
stringBuilder.Append(" (");
IEnumerator enumerator = property.GetEnumerator();
while (enumerator.MoveNext()) {
SerializedProperty childProperty = (SerializedProperty)enumerator.Current;
cacheProperties.Add(childProperty!.Copy()); // Copy is very important since .Current changes its content while enumerating
stringBuilder.Append(ObjectNames.NicifyVariableName(childProperty!.name));
stringBuilder.Append(", ");
}
if (cacheProperties.Count > 0) {
stringBuilder.Remove(stringBuilder.Length - 2, 2);
stringBuilder.Append(")");
}
else {
stringBuilder.Clear();
}
GUIContent newLabel = new($"{label}{stringBuilder}", label.tooltip);
Rect labelRect = new(position) { height = EditorGUIUtility.singleLineHeight };
Rect fieldRect = EditorGUI.PrefixLabel(labelRect, newLabel);
fieldRect.height = EditorGUIUtility.singleLineHeight;
int childCount = cacheProperties.Count;
int childIndex = 0;
float spacing = EditorGUIUtility.standardVerticalSpacing;
float fullWidth = fieldRect.width / childCount;
float widthMinusSpacing = fullWidth - spacing * (childCount - 1) / childCount;
int indentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
for (int i = 0, c = cacheProperties.Count; i < c; i++) {
SerializedProperty childProperty = cacheProperties[i];
Rect childFieldRect = new(fieldRect) {
x = Mathf.CeilToInt(fieldRect.x + fullWidth * childIndex),
width = widthMinusSpacing
};
EditorGUI.PropertyField(childFieldRect, childProperty, GUIContent.none);
childIndex++;
}
EditorGUI.indentLevel = indentLevel;
EditorGUI.EndProperty();
}
}
}
#endif