Using a custom inspector allows you to change the way a script is drawn in the Inspector. Sometimes you want to add extra information in the inspector for your script that isn't possible to do with a custom property drawer.
Below is a simple example of a custom object that with using a custom inspector can show more useful information.
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class InspectorExample : MonoBehaviour {
public int Level;
public float BaseDamage;
public float DamageBonus {
get {
return Level / 100f * 50;
}
}
public float ActualDamage {
get {
return BaseDamage + DamageBonus;
}
}
}
#if UNITY_EDITOR
[CustomEditor( typeof( InspectorExample ) )]
public class CustomInspector : Editor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
var ie = (InspectorExample)target;
EditorGUILayout.LabelField( "Damage Bonus", ie.DamageBonus.ToString() );
EditorGUILayout.LabelField( "Actual Damage", ie.ActualDamage.ToString() );
}
}
#endif
First we define our custom behaviour with some fields
public class InspectorExample : MonoBehaviour {
public int Level;
public float BaseDamage;
}
The fields shown above are automatically drawn (without custom inspector) when you are viewing the script in the Inspector window.
public float DamageBonus {
get {
return Level / 100f * 50;
}
}
public float ActualDamage {
get {
return BaseDamage + DamageBonus;
}
}
These properties are not automatically drawn by Unity. To show these properties in the Inspector view we have to use our Custom Inspector.
We first have to define our custom inspector like this
[CustomEditor( typeof( InspectorExample ) )]
public class CustomInspector : Editor {
The custom inspector has to derive from Editor and needs the CustomEditor attribute. The parameter of the attribute is the type of the object this custom inspector should be used for.
Next up is the OnInspectorGUI method. This method gets called whenever the script is shown in the inspector window.
public override void OnInspectorGUI() {
base.OnInspectorGUI();
}
We make a call to base.OnInspectorGUI() to let Unity handle the other fields that are in the script. If we would not call this we would have to do more work ourselves.
Next are our custom properties that we want to show
var ie = (InspectorExample)target;
EditorGUILayout.LabelField( "Damage Bonus", ie.DamageBonus.ToString() );
EditorGUILayout.LabelField( "Actual Damage", ie.ActualDamage.ToString() );
We have to create a temporary variable that holds target casted to our custom type (target is available because we derive from Editor).
Next we can decide how to draw our properties, in this case two labelfields are enough since we just want to show the values and not be able to edit them.
Result
Before
After