需求:重写 UGUI中 Toggle 类 MyToggle 使其添加一条属性Panel
代码:
using UnityEngine;
using UnityEngine.UI;
public class MyToggle : Toggle
{
public Transform panel;
}
创建MyToggleEditor脚本
using UnityEditor;
using UnityEngine;
//CustomEditor:允许我们自定义组件的Inspect检视面板
[CustomEditor(typeof(MyToggle), true)] ///MyToggle 需要显示在Inspector的类
//CanEditMultipleObjects:可多选编辑选中物体中该属性面板
[CanEditMultipleObjects]
//重写toggle则继承UnityEditor.UI.ToggleEditor toggle编辑类(公共类则继承对应公共类Editor,自定义类则继承Editor)
public class MyToggleEditor : UnityEditor.UI.ToggleEditor
{
SerializedProperty Panel; // SerializedProperty 反射一个Unity对象
private void OnEnable()
{
base.OnEnable();
//FindProperty CustomEditor指定的GameObject脚本(MyToggle)中获取对象(Panel)以在检查器中显示。
Panel = serializedObject.FindProperty("Panel"); //查找到MyToggle中的Panel
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
EditorGUILayout.PropertyField(Panel);
serializedObject.ApplyModifiedProperties();
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
}
}
网友评论