Tri-Inspector/Editor.Extras/Drawers/ObjectReferenceDrawer.cs

67 lines
2.3 KiB
C#
Raw Normal View History

2022-01-07 12:21:36 -05:00
using TriInspector;
using TriInspector.Drawers;
using UnityEditor;
using UnityEngine;
[assembly: RegisterTriValueDrawer(typeof(ObjectReferenceDrawer<>), TriDrawerOrder.Fallback)]
namespace TriInspector.Drawers
{
public class ObjectReferenceDrawer<T> : TriValueDrawer<T>
where T : Object
{
public override TriElement CreateElement(TriValue<T> value, TriElement next)
{
2022-06-01 03:35:33 -04:00
if (value.Property.IsRootProperty)
{
return next;
}
2022-01-07 12:21:36 -05:00
return new ObjectReferenceDrawerElement(value);
}
private class ObjectReferenceDrawerElement : TriElement
{
2022-01-21 23:36:15 -05:00
private TriValue<T> _propertyValue;
2022-06-10 08:33:05 -04:00
private readonly bool _allowSceneObjects;
2022-01-07 12:21:36 -05:00
public ObjectReferenceDrawerElement(TriValue<T> propertyValue)
{
_propertyValue = propertyValue;
2022-06-10 08:33:05 -04:00
_allowSceneObjects = propertyValue.Property.PropertyTree.TargetIsPersistent &&
propertyValue.Property.TryGetAttribute(out AssetsOnlyAttribute _) == false;
2022-01-07 12:21:36 -05:00
}
public override float GetHeight(float width)
{
return EditorGUIUtility.singleLineHeight;
}
public override void OnGUI(Rect position)
{
2022-06-10 08:33:05 -04:00
var hasSerializedProperty = _propertyValue.Property
.TryGetSerializedProperty(out var serializedProperty);
2022-01-07 12:21:36 -05:00
2022-06-10 08:33:05 -04:00
var value = hasSerializedProperty ? serializedProperty.objectReferenceValue : _propertyValue.SmartValue;
2022-01-07 12:21:36 -05:00
2022-06-10 08:33:05 -04:00
EditorGUI.BeginChangeCheck();
2022-01-07 12:21:36 -05:00
2022-06-10 08:33:05 -04:00
value = EditorGUI.ObjectField(position, _propertyValue.Property.DisplayNameContent, value,
_propertyValue.Property.FieldType, _allowSceneObjects);
2022-01-07 12:21:36 -05:00
if (EditorGUI.EndChangeCheck())
{
2022-06-10 08:33:05 -04:00
if (hasSerializedProperty)
{
serializedProperty.objectReferenceValue = value;
_propertyValue.Property.NotifyValueChanged();
}
else
{
_propertyValue.SmartValue = (T) value;
}
2022-01-07 12:21:36 -05:00
}
}
}
}
}