How can I make function run in the editor only when I press a button in the inspector?

I’d like to create a script that has a button that shows in the inspector. When that button is pressed I want it to run a certain function (withing that same script) in the unity editor.

Kind of like [ExecuteInEditMode] but only when I press a button I created in the inspector instead of every frame.

@whisker-ship

Creating a custom editor window may work well for you. Here is an example.

using UnityEngine;
using UnityEditor;

public class EditModeFunctions : EditorWindow
{
    [MenuItem("Window/Edit Mode Functions")]
    public static void ShowWindow()
    {
        GetWindow<EditModeFunctions>("Edit Mode Functions");
    }

    private void OnGUI()
    {
        if (GUILayout.Button("Run Function"))
        {
            FunctionToRun();
        }
    }

    private void FunctionToRun()
    {
        Debug.Log("The function ran.");
    }
}

Let this script compile in Unity. Then, select Window > Edit Mode Functions.

97321-windowdropdown.png

Now, just click the “Run Function” button to run your function in edit mode.

97322-editmodefuncwindow.png