Neg_Utils/NEG/UI/UnityUi/Editor/OverridableNavigationDrawer.cs

114 lines
3.8 KiB
C#

using NEG.UI.UnityUi.Buttons;
using NEG.Utils.Serialization;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using ObjectField = UnityEditor.Search.ObjectField;
using Toggle = UnityEngine.UIElements.Toggle;
namespace NEG.UI.UnityUi.Editor
{
[CustomPropertyDrawer(typeof(OverridableNavigation))]
public class OverridableNavigationDrawer: PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
// Draw label
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
// Don't make child fields be indented
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
// Calculate rects
var amountRect = new Rect(position.x, position.y, 200, position.height);
var unitRect = new Rect(position.x + 35, position.y, 200, position.height);
// Draw fields - pass GUIContent.none to each so they are drawn without labels
EditorGUI.PropertyField(amountRect, property.FindAutoPropertyRelative(nameof(OverridableNavigation.Override)), GUIContent.none);
EditorGUI.PropertyField(unitRect, property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable)), GUIContent.none);
// Set indent back to what it was
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var container = new VisualElement()
{
style =
{
paddingLeft = 3,
paddingRight = -2,
flexDirection = FlexDirection.Row,
justifyContent = Justify.SpaceBetween
}
};
string name = property.name;
if (name.Length > 0)
{
name = $"{char.ToUpper(name[0])}{name[1..]}";
}
var innerContainer = new VisualElement()
{
style =
{
flexDirection = FlexDirection.Row,
justifyContent = Justify.SpaceBetween,
marginRight = 2,
flexGrow = 1
}
};
var label = new Label(name);
var enabler = new Toggle();
enabler.BindProperty(property.FindPropertyRelative("<Override>k__BackingField"));
var field = new ObjectField()
{
style =
{
flexGrow = 100
}
};
var selectableField = property.FindAutoPropertyRelative(nameof(OverridableNavigation.Selectable));
field.BindProperty(selectableField);
field.objectType = typeof(Selectable);
innerContainer.Add(label);
innerContainer.Add(enabler);
container.Add(innerContainer);
container.Add(field);
container.RegisterCallback<GeometryChangedEvent>(_ =>
{
var panel = container.panel;
var size = panel.visualTree.contentRect.size;
// magic value measured with ruler, may change in the future!
field.style.maxWidth = size.x * 0.55f + 15;
});
field.SetEnabled(enabler.value);
enabler.RegisterValueChangedCallback(v =>
{
field.SetEnabled(v.newValue);
});
return container;
}
}
}