Unity3D 使用 Editor 脚本,自定义 脚本的属性面板

1. 先有一个普通的 继承自 MonoBehaviour 的脚本.

2. 创建一个 Editor 文件夹, 写 关于 UnityEditor 的脚本 都要放在这个文件夹下,不然会编译出错.

具体的实现如下:

 1 using UnityEngine;
 2  using UnityEditor;
 3  using System.Collections;
 4  
 5  [CustomEditor(typeof(TestBehaviour))] // 这里是表示,这个Editor是哪个脚本的界面
 6  [CanEditMultipleObjects] // 可以一起编辑多个物体
 7  public class TestBehaviourInspector : Editor {  // 继承 Editor 类
 8     // 这里是定义几个你要去控制的那个脚本里参数.
 9      // moveType 是一个 enum 类型
10      SerializedProperty isPlaying, Count, moveType;
11      
12      // 初始化, 将刚声明的参数与那个脚本里面的属性相关联
13      void OnEnable() {
14          isPlaying = serializedObject.FindProperty("isPlaying");
15          Count = serializedObject.FindProperty("Count");
16          moveType = serializedObject.FindProperty("moveType");
17      }
18  
19      // Editor GUI  具体界面在这里写
20      public override void OnInspectorGUI() {
21          // 官方说要先这样
22          serializedObject.Update();
23  
24          // 使用一个 垂直 布局
25          EditorGUILayout.BeginVertical();
26  
27          // 如果是选择多个物体的情况下. 要先判断一下,这个属性上面的值是不是都相同,相同才可以一起改变
28          if (!isPlaying.hasMultipleDifferentValues) {
29              isPlaying.boolValue = EditorGUILayout.Toggle("Is Playing", isPlaying.boolValue); 
30          }
31 
32          // 这是如果处理 enum 类型
33       if (!moveType.hasMultipleDifferentValues) {
34             moveType.enumValueIndex = (int)(TestBehaviour.MoveType)EditorGUILayout.EnumPopup("Move Type", (TestBehaviour.MoveType)moveType.enumValueIndex);
35         }
36 
37          if (!Count.hasMultipleDifferentValues) {
38              Count.intValue = EditorGUILayout.IntField("Count", Count.intValue);
39  
40              // 还可以使用 Button
41              if (GUILayout.Button("Print Count")) {
42                  Debug.Log(Count.intValue);
43              }
44          }
45  
46          EditorGUILayout.EndVertical();
47  
48          // 官方说 要在这里这样一下.应用所有的修改
49          serializedObject.ApplyModifiedProperties();
50      }
51  }    
原文地址:https://www.cnblogs.com/easyfrog/p/3145212.html