批量删除Hierarchy面板中的组件

本文介绍了一种在Unity3D中批量删除Hierarchy面板中组件的方法,通过编写EditorWindow脚本实现。用户只需在指定的输入框填入组件的程序集名、命名空间和类名,点击确定按钮,即可一键删除选中物体及其子物体上的指定组件。这大大提高了在大型场景中管理组件的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

批量删除Hierarchy面板中的组件

  • 一、目的
    当场景中有很多组件需要删掉的时候,一个个删掉很麻烦,需要一键删除。

  • 二、使用方法
    Hierarchy面板中选择物体,右键,Tools->RemoveComponent,弹出面板设置好后,点击确定即可。

  • 三、代码

using System;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 批量删除组件
/// </summary>
public class RemoveComponentEditor : EditorWindow
{
    private static EditorWindow window;
    private static GameObject select;
    private static string className = "Image";//类名
    private static string dllName = "UnityEngine.UI";//程序集名
    private static string namespaceName = "UnityEngine.UI";//命名空间
    

    [MenuItem("GameObject/Tools/RemoveComponent", priority = 0)]
    public static void RemoveComponent()
    {
        select = Selection.activeGameObject;
        window = EditorWindow.GetWindow(typeof(RemoveComponentEditor));
    }

    private void OnGUI()
    {
        if (select)
        {
            GUI.Label(new Rect(20, 40, 200, 20), "程序集名:");
            dllName = GUI.TextField(new Rect(110, 40, 100, 20), dllName, 20);

            GUI.Label(new Rect(20, 80, 200, 20), "命名空间:");
            namespaceName = GUI.TextField(new Rect(110, 80, 100, 20), namespaceName, 20);

            GUI.Label(new Rect(20, 120, 200, 20), "组件名:");
            className = GUI.TextField(new Rect(110, 120, 100, 20), className, 20);
            if (GUI.Button(new Rect(20, 160, 190, 20), "确定"))
            {
                if (!string.IsNullOrEmpty(className))
                {
                    try
                    {
                        Type t = System.Reflection.Assembly.Load(dllName).GetType(namespaceName +  "." + className);
                        GameObject selectGO = select;
                        var nodes = selectGO.GetComponentsInChildren(t,true);
                        for (int i = 0; i < nodes.Length; i++)
                        {
                            DestroyImmediate(nodes[i]);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.Message);
                        window.Close();
                        return;
                    }
                }
                window.Close();
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值