拓展编辑器(二十)_面板拓展(Inspector面板

  我们的Unity脚本挂在游戏对象上时,右侧会出现它的详细信息面板,这些信息是根据脚本中声明的public可序列化变量而来的。此外,也可以通过EditorGUI来对它进行绘制,让面板更具可操作性。

Inspector面板

  EditorGUI和GUI的用法几乎完全一致,目前来说前者多用于编辑器开发,后者多用于发布后调试编辑器。即他们都是起辅助作用的。EditorGUI提供丰富的组件非常丰富,常用的绘制元素包括文本,按钮,图片和滑动框等。做一个好的编辑器,是离不开EditorGUI的。  

  如图所示,我们将EditorGUI拓展在Inspector面板上了

  实现代码如下所示:

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

public class Inspector面板 : MonoBehaviour
{
    public Vector3 scrollPos;
    public int myId;
    public string myName;
    public GameObject prefab;
    public MyEnum myEnum = MyEnum.One;
    public bool toogle1;
    public bool toogle2;
    public enum MyEnum
    {
        One=1,
        Two
    }
}

#if UNITY_EDITOR
[CustomEditor(typeof(Inspector面板))]
public class Inspector面板Editor : Editor
{
    private bool m_EnableToogle;
    public override void OnInspectorGUI()
    {
        //获取脚本对象
        Inspector面板 script = target as Inspector面板;
        //绘制滚动条
        script.scrollPos =
                EditorGUILayout.BeginScrollView(script.scrollPos, false, true);

        script.myName = EditorGUILayout.TextField("text", script.myName);
        script.myId = EditorGUILayout.IntField("text", script.myId);
        script.prefab = EditorGUILayout.ObjectField("GameObject", script.prefab,
            typeof(GameObject), true) as GameObject;


        //绘制按钮
        EditorGUILayout.BeginHorizontal();
        GUILayout.Button("1");
        GUILayout.Button("2");
        script.myEnum = (Inspector面板.MyEnum)EditorGUILayout.EnumPopup("MyEnum:", 
            script.myEnum);
        EditorGUILayout.EndHorizontal();

        //Toogle组件
        m_EnableToogle = EditorGUILayout.BeginToggleGroup("EnableToogle", m_EnableToogle);
        script.toogle1 = EditorGUILayout.Toggle("toogle1", script.toogle1);
        script.toogle2 = EditorGUILayout.Toggle("toogle2", script.toogle2);
        EditorGUILayout.EndToggleGroup();

        EditorGUILayout.EndScrollView();
    }
}
#endif

  在上述代码中,我们将脚本部分和Editor部分的代码合在一个文件中。如果需要拓展的面板比较复杂,建议分成两个文件存放,一个是脚本另外一个是Editor文件。

PS:关于EditorGU类中的方法,可以在Unity的API中查询,也可以参考一下这个:https://www.cnblogs.com/caymanlu/p/5722549.html

猜你喜欢

转载自www.cnblogs.com/llllllvty/p/10017713.html