Unity编辑器扩展 自定义脚本属性面板基础篇

2022-08-12 14:17:19

开发中,如果使用插件会发现插件的组件,在属性面板上的设计非常方便,看着很高大上,他们是怎么做到的呢

基础

  • 在Editor文件夹下,创建我们的属性面板编辑脚本
  • using UnityEditor的命名空间
  • 继承Editor

测试脚本

using UnityEngine;

public class ComponentInspector:MonoBehaviour {
       public bool PropertyBool;
       public TestEnum PropertyEnum;
       public int PropertyValue;
}
public enum TestEnum {

        Test1 = 0,
        Test2 = 1

}

Editor脚本

using UnityEngine;
using UnityEditor;

//ComponentInspector:目标脚本
[CustomEditor(typeof(ComponentInspector))]
public class ComponentInspectorEditor : Editor{
    
     private SerializedObject @object;
     
     private SerializedProperty m_PropertyBool;
     private SerializedProperty m_PropertyEnum;
     private SerializedProperty m_PropertyValue;

     private void OnEnable(){
            @object = new SerializedObject(target);
            //寻找对应的属性
            m_PropertyBool = @object.FindProperty("PropertyBool");
            m_PropertyEnum= @object.FindProperty("PropertyEnum");
            m_PropertyValue= @object.FindProperty("PropertyValue");
     }

     public override void OnInspectorGUI(){
            @object.Update();
            SerializedProperty property = @object.GetIterator();
            while (property.NextVisible(true))
            {
                using (new EditorGUI.DisabledScope("m_Script" == property.propertyPath))
                {
                    EditorGUILayout.PropertyField(property, true);
                    break;
                }
            }
            //开始设计属性面板
            EditorGUILayout.PropertyField(m_PropertyBool);
            if(m_PropertyBool .boolValue){
                    EditorGUILayout.PropertyField(m_PropertyEnum);
                    if(m_PropertyEnum.enumValueIndex == 0){
                           EditorGUILayout.PropertyField(m_PropertyValue);
                    }
            }
            
            @object.ApplyModifiedProperties();
     }
}

简单看一下效果吧

  • 作者:贪小心
  • 原文链接:https://blog.csdn.net/Liu_ChangC/article/details/122878770
    更新时间:2022-08-12 14:17:19