Skip to content

Instantly share code, notes, and snippets.

@wonkee-kim
Last active January 7, 2025 22:10
Show Gist options
  • Save wonkee-kim/cb69badc769bc3f3055030d92a7c8bac to your computer and use it in GitHub Desktop.
Save wonkee-kim/cb69badc769bc3f3055030d92a7c8bac to your computer and use it in GitHub Desktop.
Unity EditorButton attribute that shows buttons of methods in the inspector.
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace AnimalCompany
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class EditorButtonAttribute : Attribute
{
public string Label { get; }
public EditorButtonAttribute() : this(label: null) { }
public EditorButtonAttribute(string label)
{
Label = label;
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(MonoBehaviour), true)]
public class EditorButtonDrawer : Editor
{
private MethodInfo[] _buttonMethods;
private EditorButtonAttribute[] _buttonAttributes;
private void OnEnable()
{
_buttonMethods = target
.GetType()
.GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetCustomAttribute<EditorButtonAttribute>(inherit: true) != null && m.GetParameters().Length == 0)
.ToArray();
_buttonAttributes = _buttonMethods
.Select(m => m.GetCustomAttribute<EditorButtonAttribute>(inherit: true))
.ToArray();
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (_buttonMethods == null || _buttonMethods.Length == 0)
return;
GUILayout.Space(10f);
for (int i = 0; i < _buttonMethods.Length; i++)
{
EditorButtonAttribute attribute = _buttonAttributes[i];
if (attribute != null)
{
GUILayout.Space(5f);
MethodInfo method = _buttonMethods[i];
if (GUILayout.Button(attribute.Label ?? method.Name))
{
method.Invoke(target, null);
}
}
}
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment