Skip to content

Instantly share code, notes, and snippets.

@fangzhangmnm
Last active January 9, 2026 07:02
Show Gist options
  • Select an option

  • Save fangzhangmnm/d6a4f53bb2661b1bf8266ddfcf28dcc5 to your computer and use it in GitHub Desktop.

Select an option

Save fangzhangmnm/d6a4f53bb2661b1bf8266ddfcf28dcc5 to your computer and use it in GitHub Desktop.
/*********
This script adds a button to the Unity Inspector for any parameterless method
by adding a [Button] attribute above the method definition.
Warning: Code is blind-generated by AI without human inspection, use at your own risk.
Usage:
[Button]
private void MyMethod()
{
// Method logic here
}
Author: chatgpt.com
Supervisor: fangzhangmnm, Jan.9 2026
License: MIT
Reference: https://github.com/madsbangh/EasyButtons/
*********/
using System;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
#endif
/// <summary>
/// Put [Button] above any parameterless method in a MonoBehaviour
/// to draw a clickable button for it in the Inspector.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ButtonAttribute : Attribute { }
#if UNITY_EDITOR
/// <summary>
/// Global editor that adds buttons for any [Button] methods on MonoBehaviours.
/// </summary>
[CustomEditor(typeof(MonoBehaviour), true)]
public class ButtonEditor : Editor
{
public override void OnInspectorGUI()
{
// Draw the normal inspector first
DrawDefaultInspector();
// Then draw buttons for any [Button] methods
var type = target.GetType();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var method in methods)
{
if (!Attribute.IsDefined(method, typeof(ButtonAttribute)))
continue;
var parameters = method.GetParameters();
if (parameters.Length > 0)
{
EditorGUILayout.HelpBox(
$"[Button] '{method.Name}' must have no parameters.",
MessageType.Warning
);
continue;
}
string label = ObjectNames.NicifyVariableName(method.Name);
if (GUILayout.Button(label))
{
foreach (var t in targets) // support multi-object selection
{
method.Invoke(t, null);
}
}
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment