Adding Buttons to a Custom Inspector

Checked with version: 4.3

-

Difficulty: Intermediate

In Unity we can add buttons to editor windows so that we can call our functions from our scripts. Doing so give us the ability to write scripts specifically to improve our workflow. In this video you will learn how to create buttons in a custom inspector and how to tie them to functions that exist in our scripts.

Adding Buttons to a Custom Inspector

Intermediate Interface & Essentials

ObjectBuilderScript

Code snippet

using UnityEngine;
using System.Collections;

public class ObjectBuilderScript : MonoBehaviour 
{
    public GameObject obj;
    public Vector3 spawnPoint;

    
    public void BuildObject()
    {
        Instantiate(obj, spawnPoint, Quaternion.identity);
    }
}
#pragma strict

var obj : GameObject;
var spawnPoint : Vector3;


function BuildObject()
{
    Instantiate(obj, spawnPoint, Quaternion.identity);
}
import UnityEngine
import System.Collections


public class ObjectBuilderScript(MonoBehaviour):

    public obj as GameObject

    public spawnPoint as Vector3

    
    
    public def BuildObject():
        Instantiate(obj, spawnPoint, Quaternion.identity)

ObjectBuilderEditor

Code snippet

using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomEditor(typeof(ObjectBuilderScript))]
public class ObjectBuilderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();
        
        ObjectBuilderScript myScript = (ObjectBuilderScript)target;
        if(GUILayout.Button("Build Object"))
        {
            myScript.BuildObject();
        }
    }
}
#pragma strict

@CustomEditor (ObjectBuilderScript)
public class ObjectBuilderEditor extends Editor
{
    function OnInspectorGUI()
    {
        DrawDefaultInspector();
        
        var myScript : ObjectBuilderScript = target;
        if(GUILayout.Button("Build Object"))
        {
            myScript.BuildObject();
        }
    }
}
import UnityEngine
import System.Collections
import UnityEditor


[CustomEditor(typeof(ObjectBuilderScript))]
public class ObjectBuilderEditor(Editor):

    public override def OnInspectorGUI():
        DrawDefaultInspector()
        
        myScript = (target cast ObjectBuilderScript)
        if GUILayout.Button('Build Object'):
            myScript.BuildObject()