Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Expose methodes to the inspectors with buttons.

Discussion in '2D' started by bytewav, Sep 30, 2016.

  1. bytewav

    bytewav

    Joined:
    Jan 8, 2013
    Posts:
    8
    You can extend the unity inspector with the custom attribute CustomEditor. Add this .cs to an Editor folder:
    //


    using UnityEngine;
    using System.Collections;
    using UnityEditor;
    using System;
    using System.Collections.Generic;
    using System.Reflection;

    public class ShowMethod : CustomAttribute
    {
    }

    [CustomEditor(typeof(Behaviour),true)]
    public class CustomInspector : Editor
    {
    public override void OnInspectorGUI()
    {
    base.OnInspectorGUI();

    Type myType = target.GetType();
    List<MethodInfo> Methods = new List<MethodInfo>(myType.GetMethods());

    foreach (MethodInfo method in Methods)
    {
    object[] Attributes = method.GetCustomAttributes(typeof(ShowMethod),false);
    bool ShowMethodPresent = Attributes.Length > 0;

    if(ShowMethodPresent)
    if(GUILayout.Button(method.Name))
    {
    method.Invoke(target,null);
    }
    }
    }
    }

    /*

    then use it in your script like so:

    class yourClass : MonoBehaviour
    {
    [ShowMethod]
    void SomeThing()
    {}
    }
    */
     
    Last edited: Jan 19, 2017