Tri-Inspector/Editor.Extras/Drawers/ButtonDrawer.cs
2022-05-09 10:29:33 +03:00

57 lines
1.6 KiB
C#

using System;
using System.Reflection;
using TriInspector;
using TriInspector.Drawers;
using UnityEditor;
using UnityEngine;
[assembly: RegisterTriAttributeDrawer(typeof(ButtonDrawer), TriDrawerOrder.Drawer)]
namespace TriInspector.Drawers
{
public class ButtonDrawer : TriAttributeDrawer<ButtonAttribute>
{
public override string CanDraw(TriProperty property)
{
if (property.MemberInfo is MethodInfo mi && mi.GetParameters().Length == 0)
{
return null;
}
return "[Button] valid only on methods without parameters";
}
public override float GetHeight(float width, TriProperty property, TriElement next)
{
return EditorGUIUtility.singleLineHeight;
}
public override void OnGUI(Rect position, TriProperty property, TriElement next)
{
var name = Attribute.Name ?? property.DisplayName;
if (GUI.Button(position, name))
{
InvokeButton(property, Array.Empty<object>());
}
}
private static void InvokeButton(TriProperty property, object[] parameters)
{
var methodInfo = (MethodInfo) property.MemberInfo;
property.ModifyAndRecordForUndo(targetIndex =>
{
try
{
var parentValue = property.Parent.GetValue(targetIndex);
methodInfo.Invoke(parentValue, parameters);
}
catch (Exception e)
{
Debug.LogException(e);
}
});
}
}
}