You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让自定义Inspector脚本应用于所有MonoBehavior子类?

实现覆盖所有MonoBehaviour子类的自定义编辑器

要让自定义编辑器作用于所有MonoBehaviour的子类,只需要在[CustomEditor]特性中添加第二个参数editorForChildClasses = true,这个参数会让编辑器自动匹配目标类型的所有子类,而非仅精确匹配目标类型本身。

基础实现代码

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(MonoBehaviour), true)]
public class AllMonoBehaviourEditor : Editor
{
    public override void OnInspectorGUI()
    {
        // 保留默认Inspector的所有功能
        DrawDefaultInspector();

        // 在这里添加你的自定义功能,示例:一个通用按钮
        if (GUILayout.Button("所有MonoBehaviour子类通用按钮"))
        {
            MonoBehaviour targetBehaviour = target as MonoBehaviour;
            Debug.Log($"触发自定义逻辑:选中对象 {targetBehaviour.name}");
        }
    }
}

关键说明

  • [CustomEditor(typeof(MonoBehaviour), true)]中的第二个布尔参数editorForChildClasses是核心,设置为true后,编辑器会对所有继承自MonoBehaviour的类生效。
  • 调用DrawDefaultInspector()可以保留原有脚本的Inspector界面,避免完全替换掉默认的编辑功能;如果不需要默认界面,可以直接编写自定义逻辑。
  • 上述默认实现会影响Unity自带的组件(比如Transform、Collider),如果只想作用于你自己编写的脚本,可以添加类型判断过滤:

过滤Unity自带组件的版本

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(MonoBehaviour), true)]
public class CustomMonoBehaviourEditor : Editor
{
    public override void OnInspectorGUI()
    {
        System.Type targetType = target.GetType();
        // 仅对非UnityEngine命名空间下的自定义脚本生效
        if (!string.IsNullOrEmpty(targetType.Namespace) && !targetType.Namespace.StartsWith("UnityEngine"))
        {
            DrawDefaultInspector();
            
            if (GUILayout.Button("自定义脚本专属按钮"))
            {
                Debug.Log($"自定义脚本 {targetType.Name} 触发逻辑");
            }
        }
        else
        {
            // 对于Unity自带组件,仅显示默认Inspector
            DrawDefaultInspector();
        }
    }
}

内容的提问来源于stack exchange,提问作者MetallicWaste

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 03:49:58