准备
- cs文件会写在Editor文件夹中
- 需要与原始脚本进行关联
- 脚本继承Editor
//步骤1:引入编辑器的命名空间,检视器属于编辑器开发范畴
using UnityEditor;
[CustomEditor(typeof(Player))]//步骤3:将编辑器开发脚本与需要编辑的组件脚本建立外挂关联关系
//外挂脚本因为存储在Editor目录下,所以不会被打入最终的游戏包
public class PlayerEditor : Editor //步骤2:继承Editor类,使用编辑器相关的成员变量和生命周期函数
{
private Player _Component;
//步骤4:需要在当前的外挂脚本中,获得需要被扩展的Player组件对象
//当关联组件所在对象被选中或组件被添加时,调用
private void OnEnable()
{
//步骤5:获取Player组件对象
_Component = target as Player;
}
//当关联组件所在对象被取消或组件被移除时,调用
private void OnDisable()
{
_Component = null;
}
// 用于绘制检视面板的生命周期函数
public override void OnInspectorGUI()
{
// 绘制面板属性
}
}
绘制标题
- EditorGUILayout.LabelField:显示标题
public override void OnInspectorGUI()
{
EditorGUILayout.LabelField("人物相关属性");
}
绘制基本数据类型
- EditorGUILayout.IntField 数字
- EditorGUILayout.TextField 文本
- EditorGUILayout.FloatField 浮点数
- EditorGUILayout.Toggle 布尔
- EditorGUILayout.Vector3Field 向量
- EditorGUILayout.ColorField 颜色
public override void OnInspectorGUI()
{
_Component.ID = EditorGUILayout.IntField("玩家ID", _Component.ID);
//文本
_Component.Name = EditorGUILayout.TextField("玩家名称", _Component.Name);
//浮点数
_Component.Atk = EditorGUILayout.FloatField("玩家攻击力", _Component.Atk);
//布尔
_Component.isMan = EditorGUILayout.Toggle("是否为男性", _Component.isMan);
//向量
_Component.HeadDir = EditorGUILayout.Vector3Field("头部方向", _Component.HeadDir);
//颜色
_Component.Hair = EditorGUILayout.ColorField("头发颜色", _Component.Hair);
}
绘制对象数据类型
EditorGUILayout.ObjectField(string label, UnityEngine.Object obj, Type objType, bool allowSceneObjects, params GUILayoutOption[] options)
- 参数1:标题
- 参数2:原始组件的值
- 参数3:成员变量的类型
- 参数4:是否可以将场景中的对象拖拽给这个成员变量
绘制枚举数据类型
- 单选枚举 EditorGUILayout.EnumPopup
- 多选枚举 EditorGUILayout.EnumFlagsField
public override void OnInspectorGUI()
{
//单选枚举(标题, 组件上的原始值)
_Component.Pro = (PlayerProfression)EditorGUILayout.EnumPopup("玩家职业", _Component.Pro);
//多选枚举(标题, 组件上的原始值)
_Component.LoveColor = (PlayerLoveColor)EditorGUILayout.EnumFlagsField("玩家喜欢的颜色", _Component.LoveColor);
}
绘制扩展数据类型(集合等)
public override void OnInspectorGUI()
{
//更新可序列化数据
serializedObject.Update();
//通过成员变量名找到组件上的成员变量
SerializedProperty sp = serializedObject.FindProperty("Items");
//可序列化数据绘制(取到的数据,标题,是否将所有获得的序列化数据显示出来)
EditorGUILayout.PropertyField(sp, new GUIContent("道具信息"), true);
//将修改的数据,写入到可序列化的原始数据中
serializedObject.ApplyModifiedProperties();
}
绘制滑动条
- EditorGUILayout.Slider(标题,原始变量,最小值,最大值)
public override void OnInspectorGUI()
{
_Component.Atk = EditorGUILayout.Slider(new GUIContent("玩家攻击力"), _Component.Atk, 0, 100);
}
绘制消息框

- EditorGUILayout.HelpBox("错误", MessageType.Error); 错误消息框
- EditorGUILayout.HelpBox("警告", MessageType.Warning); 警告消息框
- EditorGUILayout.HelpBox("信息", MessageType.Info); 信息消息框
绘制按钮
横向排列的绘制
- EditorGUILayout.BeginHorizontal(); 开始横向绘制
- EditorGUILayout.EndHorizontal(); 结束横向绘制
评论区