Unity provides an ability to override the OnInspectorGUI
function which is called when drawing an inspector window for a specific script.
The way it works is you can just create a new class derived from Editor class and tell the unity to create our custom inspector windows for your specific script.
And then in your OnInspectorGUI
you can ask unity to draw all sorts of controls including buttons, color dialogs, sliders, etc!
Now to make a simple button with the traditional "Hello World" text, follow this code:
using UnityEngine;
using UnityEditor;
public class MyScript : MonoBehaviour
{
public bool doesntMatter;
}
[CustomEditor(typeof(MyScript))]
public class MyScriptEditor : Editor
{
void OnInspectorGUI()
{
var myScript = target as MyScript;
myScript.doesntMatter= EditorGUILayout.Toggle("Hello World"); //Returns true when user clicks
}
}
Now if you've got a good grasp, here's something that you might actually need when creating custom inspector windows:
When the user toggles a checkmark, more variables wqill be shown to the user.
using UnityEngine;
using UnityEditor;
public class MyScript2 : MonoBehaviour
{
public bool show = false;
public int num1;
public float num2;
public bool anotherToggle = false;
public GameObject go;
}
[CustomEditor(typeof(MyScript2))]
public class MyScript2Editor : Editor
{
void OnInspectorGUI()
{
var myScript2 = target as MyScript2;
myScript2.show = EditorGUILayout.Toggle("Show Hidden Values");
myScript2.anotherToggle = EditorGUILayout.Toggle("Show Another Hidden Value");
if(myScript2.show)
myScript2.num1 = EditorGUILayout.IntField("Enter a number:", myScript2.num1);
myScript2.num2 = EditorGUILayout.Slider("Choose float between 1 to 10:", myScript2.num2, 0, 10f);
if(myScript2.anotherToggle)
myScript2.go = EditorGUILayout.ObjectField("Very hidden gameObject:", go, typeof(GameObject));
}
}
Hope this helped you create your first inspector windows :)