Editor.OnInspectorGUI

感觉自己要把Unity的Manual手册搬上来了。。。不过为了加深对Unity的操作和理解,还是想要这样一步步的记录一下。因为这个函数太常见了,所以就加强一下记忆。

Editor.OnInspectorGUI

通过实现该函数来制作自定义的Inspector面板。

在这个函数内部你可以添加自定义的GUI来展示类的Inspector面板。

 注意:要想这个函数工作,必须被重写

来看一下官方给出的示例:

using UnityEngine;
using System.Collections;
using UnityEditor;

// Creates a custom Label on the inspector for all the scripts named ScriptName
// Make sure you have a ScriptName script in your
// project, else this will not work.
[CustomEditor(typeof(ScriptName))]
public class TestOnInspector : Editor
{
    public override void OnInspectorGUI()
    {
        GUILayout.Label ("This is a Label in a Custom Editor");
    }
}

实验如下:

我创建了一个空的GameObject,然后创建了Test_Y.cs和TestYEditor.cs,把Test_Y.cs拖拽到GameObject上,如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test_Y : MonoBehaviour
{
    public bool ins;
    public string str;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Test_Y))]
public class TestYEditor : Editor
{
    public override void OnInspectorGUI()
    {
        Test_Y test = (Test_Y)target;
        Undo.RecordObject(target, target.name);
        //Inspector(); 如果自己定义的展示过多,那就封装成一个函数放在这里
        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
        GUILayout.Label("This is a Custom Editor");
        
        test.ins = EditorGUILayout.Toggle("展示", test.ins);
        test.str = EditorGUILayout.TextField("说点话吧", test.str);
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 结果如下:

Editor.OnInspectorGUI

不过一般情况下,如果是自己想要自定义面板的话,是放在一个文件里的,比如说这样:

public class TestY:MonoBehaviour
{
  ....
  [CustomEditor(typeof(TestY))]
  public class TestY_Editor:Editor
  {
     public override void OnInspectorGUI()
        {
         ....
        }
  }
}

注意:EditorWindow自定义的是OnGUI(),这里自定义的是OnInspectorGUI()