Building a Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
1
2
3
4
5
6
7
using UnityEngine;
 
public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using UnityEngine;
using UnityEditor;
 
[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        playerScript.health = EditorGUILayout.IntField("Health", playerScript.health);
        playerScript.maxHealth = EditorGUILayout.IntField("Max-Health", playerScript.maxHealth);
 
        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal("box");
        if (playerScript.maxHealth > 0)
        {
            EditorGUILayout.LabelField("Health %", playerScript.health * 100 / playerScript.maxHealth + "%");
        }
        EditorGUILayout.EndHorizontal();
    }
}