Skip to content

Instantly share code, notes, and snippets.

@romainPechot
Created December 6, 2016 17:09
Show Gist options
  • Save romainPechot/8eba1f897a0e2dd655d11d130b810c93 to your computer and use it in GitHub Desktop.
Save romainPechot/8eba1f897a0e2dd655d11d130b810c93 to your computer and use it in GitHub Desktop.
Custom Tweak Propertie Attribute Add Button to Inspector w/out complete CustomInspector (put InspectorButtonPropertyDrawer.cs inside an Editor folder)
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
// format from this thread : https://www.reddit.com/r/Unity3D/comments/1s6czv/inspectorbutton_add_a_custom_button_to_your/
[System.AttributeUsage(System.AttributeTargets.Field)]
public class InspectorButtonAttribute : PropertyAttribute
{
public const float DefaultButtonWidth = 80f;
public string MethodName;
public float ButtonWidth = DefaultButtonWidth;
public InspectorButtonAttribute(string MethodName, float ButtonWidth = DefaultButtonWidth)
{
this.MethodName = MethodName;
this.ButtonWidth = ButtonWidth;
}// InspectorButtonAttribute()
}// class InspectorButtonAttribute : PropertyAttribute
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Reflection;
// put this script inside an Editor folder.
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(InspectorButtonAttribute))]
public class InspectorButtonPropertyDrawer : PropertyDrawer
{
private MethodInfo _eventMethodInfo = null;
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
InspectorButtonAttribute inspectorButtonAttribute =(InspectorButtonAttribute)attribute;
Rect buttonRect = new Rect(position.x + (position.width - inspectorButtonAttribute.ButtonWidth) * 0.5f, position.y, inspectorButtonAttribute.ButtonWidth, position.height);
if(GUI.Button(buttonRect, label.text))
{
System.Type eventOwnerType = prop.serializedObject.targetObject.GetType();
string eventName = inspectorButtonAttribute.MethodName;
if(_eventMethodInfo == null)
_eventMethodInfo = eventOwnerType.GetMethod(eventName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if(_eventMethodInfo != null)
_eventMethodInfo.Invoke(prop.serializedObject.targetObject, null);
else
Debug.LogWarning(string.Format("InspectorButton: Unable to find method {0} in {1}", eventName, eventOwnerType));
}
}// OnGUI()
}// class InspectorButtonPropertyDrawer : PropertyDrawer
#endif// UNITY_EDITOR
using UnityEngine;
public class InspectorButtonTest : MonoBehaviour
{
[InspectorButton("ToggleEnable")]
public bool switchEnable = false;
private void Start() { }
private void ToggleEnable()
{
enabled = !enabled;
}// ToggleEnable()
}// class InspectorButtonTest : MonoBehaviour
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment