Skip to content

Instantly share code, notes, and snippets.

@Novack
Created November 16, 2016 04:04
Show Gist options
  • Save Novack/2c20473951870c44c943f90fd2925951 to your computer and use it in GitHub Desktop.
Save Novack/2c20473951870c44c943f90fd2925951 to your computer and use it in GitHub Desktop.
Add editor buttons to your MonoBehaviours methods
using UnityEditor;
using UnityEngine;
namespace BitStrap
{
/// <summary>
/// Custom editor for all MonoBehaviour scripts in order to draw buttons for all button attributes (<see cref="ButtonAttribute"/>).
/// </summary>
[CustomEditor( typeof( MonoBehaviour ), true, isFallback = true )]
[CanEditMultipleObjects]
public class BehaviourButtonsEditor : Editor
{
private ButtonAttributeHelper helper = new ButtonAttributeHelper();
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
helper.DrawButtons();
}
private void OnEnable()
{
helper.Init( target );
}
}
}
namespace BitStrap
{
/// <summary>
/// Put this attribute above one of your MonoBehaviour method and it will draw
/// a button in the inspector automatically.
///
/// NOTE: the method must not have any params and can not be static.
///
/// <code>
/// <para>[Button]</para>
/// <para>public void MyMethod()</para>
/// <para>{</para>
/// <para> Debug.Log( "HELLO HELLO HELLO!!" );</para>
/// <para>}</para>
/// </code>
/// </summary>
[System.AttributeUsage( System.AttributeTargets.Method )]
public class ButtonAttribute : System.Attribute
{
}
}
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace BitStrap
{
/// <summary>
/// Searches through a target class in order to find all button attributes (<see cref="ButtonAttribute"/>).
/// </summary>
public class ButtonAttributeHelper
{
private static object[] emptyParamList = new object[0];
private IList<MethodInfo> methods = new List<MethodInfo>();
private Object targetObject;
public void Init(Object targetObject)
{
this.targetObject = targetObject;
methods =
targetObject.GetType()
.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m =>
m.GetCustomAttributes(typeof(ButtonAttribute), false).Length == 1 &&
m.GetParameters().Length == 0 &&
!m.ContainsGenericParameters
).ToList();
}
public void DrawButtons()
{
if (methods.Count > 0)
{
EditorGUILayout.HelpBox("Click to execute methods!", MessageType.None);
ShowMethodButtons();
}
}
private void ShowMethodButtons()
{
foreach (MethodInfo method in methods)
{
string buttonText = ObjectNames.NicifyVariableName(method.Name);
if (GUILayout.Button(buttonText))
{
method.Invoke(targetObject, emptyParamList);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment