Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created February 16, 2019 07:22
Show Gist options
  • Save beardordie/9ce119c3505742ac7eaf8226519310cb to your computer and use it in GitHub Desktop.
Save beardordie/9ce119c3505742ac7eaf8226519310cb to your computer and use it in GitHub Desktop.
Unity - minimalist Button inspector drawer for zero-parameter methods
using System;
using UnityEngine;
#if UNITY_EDITOR
using System.Linq;
using System.Reflection;
using UnityEditor;
#endif
public class ButtonAttribute : Attribute
{
}
#if UNITY_EDITOR
[CustomEditor(typeof(MonoBehaviour), true)]
public class MonoBehaviourEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
DrawButtons();
}
public void DrawButtons()
{
// Get all methods with no parameters
var methods = target.GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Where(m => m.GetParameters().Length == 0);
foreach (var method in methods)
{
// If the method has the [Button] attribute
if (Attribute.GetCustomAttribute(method, typeof(ButtonAttribute)) != null)
{
// Draw the button and if clicked, invoke the method
if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name)))
{
foreach (var t in targets)
{
method.Invoke(t, null);
}
}
}
}
}
}
#endif
@beardordie
Copy link
Author

Usage: in your MonoBehaviours, add the [Button] attribute before any method with zero parameters that you'd like a handy inspector-clickable button for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment