Unity editor extension (3) - expand the Inspector window

1. The original class inherits MonoBehaviour, such as

public class Map : MonoBehaviour
{
    public int x;
    public int y;
}

You can see the original effect, as shown below
insert image description here

2. Create an editor class, inherit Editor, and add CustomEditor annotations

Next we need to create a class that inherits Editor and add CustomEditor annotations, the code is as follows

//typeof里写要重写Inpsctor事件的类。这里是Map
[CustomEditor(typeof(Map))]
public class MapEditor : Editor
{
    
}

3. Override the OnInspectorGUI() method

code show as below

[CustomEditor(typeof(Map))]
public class MapEditor : Editor
{
    public override void OnInspectorGUI()
    {
        //绘制原来的窗口,如不增加此行代码。那么就不会绘制原有的变量
        DrawDefaultInspector();

        //接下来,可以在下面添加你个性化的组件
        
        //添加一个按钮
        if (GUILayout.Button("测试"))
        {
            Debug.Log("test");
        }
    }
}

Our usual needs are to add buttons or other operations on the original basis, so here the core DrawDefaultInspector(); should be added, which will draw the original variables. If you don't add it, the original variable will not be displayed unless you write it yourself.

Well, the effect after writing is as follows, and the button comes out.
insert image description here
In addition, since we rewrite the window for Map, the common business is to get the Map class. You can get the map through the following code

Map map = target as Map;

The overall code is as follows

[CustomEditor(typeof(Map))]
public class MapEditor : Editor
{
    private Map map;
    
    public override void OnInspectorGUI()
    {
        //绘制原来的窗口,如不增加此行代码。那么就不会绘制原有的变量
        DrawDefaultInspector();

        //接下来,可以在下面添加你个性化的组件
        
        //添加一个按钮
        if (GUILayout.Button("测试"))
        {
            Debug.Log("test");
            
            //拿到原脚本
            map = target as Map;
            Debug.Log($"map.x:{map.x} map.y:{map.y}");
        }

        
    }
}

Guess you like

Origin blog.csdn.net/aaa27987/article/details/130071370