自定义Inspector(一)

作者:追风剑情 发布于:2017-5-8 14:50 分类:Unity3d

一、创建Custom.cs并把它挂在一个GameObject上


using UnityEngine;
public class Custom : MonoBehaviour {

}


二、创建CustomInspector.cs并放在Assets/Editor目录下


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

[CustomEditor(typeof(Custom))]
[CanEditMultipleObjects]
public class CustomInspector : Editor
{
    protected Custom mCustom;
    protected virtual void OnEnable()
    {
        mCustom = target as Custom;
    }

    private bool DrawHeader(string text)
    {
        string key = text;

        bool state = EditorPrefs.GetBool(key, true);

        if (!state) GUI.backgroundColor = new Color(0.8f, 0.8f, 0.8f);
        GUILayout.BeginHorizontal();
        GUI.changed = false;

        text = "<b><size=11>" + text + "</size></b>";
        if (state) text = "\u25BC " + text;
        else text = "\u25BA " + text;
        if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state;

        if (GUI.changed) EditorPrefs.SetBool(key, state);

        GUILayout.EndHorizontal();
        GUI.backgroundColor = Color.white;
        if (!state) GUILayout.Space(3f);
        return state;
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();//保留Unity自动生成的Inspector

        if (DrawHeader("Scene Edit"))
        {
            //后面的Unity版本去掉了"AS TextArea",可用其它样式代替,如"GroupBox"
            EditorGUILayout.BeginVertical("AS TextArea", GUILayout.MinHeight(10f));
            EditorGUI.BeginDisabledGroup(true);//true:禁用以下操作

            if (GUILayout.Button("加载Config", GUILayout.Width(255)))
            {
                
            }

            if (GUILayout.Button("读取当前关卡", GUILayout.Width(255)))
            {
                
            }

            if (GUILayout.Button("生成随机关卡", GUILayout.Width(255)))
            {
                
            }

            if (GUILayout.Button("保存随机关卡", GUILayout.Width(255)))
            {
                
            }

            EditorGUI.EndDisabledGroup();
            EditorGUILayout.EndVertical();
            SceneView.RepaintAll();
        }
    }
}


测试

收起状态

33333.png

展开状态

11111.png

禁用状态 (即EditorGUI.BeginDisabledGroup(true))

2222.png

Unity Bug:在Inspector中显示List或Array时,第0号元素如果无法正常展开,可以对字段添加[NonReorderableAttribute]特性解决。如下图所示。

1111.png

22222.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号