Draw a custom button under a variable

I whant to draw this button: 183997-screenshot-1.png

Below “Play on awake” bool, how i can done this? this is my custom editor script:

    public class SFXEditor : Editor
    {
        public override void OnInspectorGUI()
        {
            if (GUILayout.Button("Play Clip"))
            {
                //Do Something.        
            }
        }
    }

Hey there,

Couple of ways to do that:

1) Order of base.OnInspectorGUI

(Easiest, but not flexible)

Since OnInspectorGUI is an override method of the Editor base class, there is a base.OnInspectorGUI() call you can perform that will draw the “regular” inspector. Depending on the order of the call and your button code in your OnInspectorGUI method, the button will be either drawn before or after the “regular” inspector block:

public override void OnInspectorGUI()
{
    if (GUILayout.Button("Play Clip"))
    {            
    }
    base.OnInspectorGUI();
}

public override void OnInspectorGUI()
{
    base.OnInspectorGUI();
    if (GUILayout.Button("Play Clip"))
    {            
    }
}

Just using the regular GUI + custom button you cannot get more granular than this.

2) Only custom GUI

(More work, more flexible)

If you want the button to go between other UI-Elements, you can just leave the base.OnInspectorGUI() call out and code the whole Editor GUI on your own, using EditorGUILayout methods. This is a bit more work and pretty unflexible when adding new public fields, so I usually wouldn’t go that way.

public override void OnInspectorGUI()
{
    TestScript myTarget = (target as TestScript);

    myTarget.playOnAwake = EditorGUILayout.Toggle("Play On Awake", myTarget.playOnAwake);

    if (GUILayout.Button("Play Clip"))
    {
            
    }

    myTarget.someOtherValue = EditorGUILayout.FloatField("Some Other Value", myTarget.someOtherValue);
}

3) Button Attribute

(My fav)

Probably the way I would go here is to add some code for a [Button] editor attribute to your project. You can find different implementations for this on the internet, but the basic idea is to add your own editor attribute that can turn any of your methods into a button without adding specific GUI code to that class. Here’s an example.

public class TestScript : MonoBehaviour
{
    public bool playOnAwake = true;
    public float someOtherValue = 10f;

    [Button]
    public void PlayClip()
    {

    }
}