Unity遍历Hierarchy上的所有物体并清除指定组件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class ClearComponent
{

    [MenuItem("我的编辑器/多个物体组件清除")]
    static void ClearComponentMore()
    {
        var allGos = Resources.FindObjectsOfTypeAll(typeof(GameObject));
        var previousSelection = Selection.objects;
        Selection.objects = allGos;
        var selectedTransforms = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
        Selection.objects = previousSelection;
        foreach (var trans in selectedTransforms)
        {
            //先显示所有物体 
            trans.gameObject.SetActive(true);
        }

        //再清除模型上的脚本
        Transform[] currentObject = null;
        currentObject = Selection.transforms;
        for (int index = 0; index < currentObject.Length; index++)
        {
            currentObject[index].gameObject.SetActive(true);
            foreach (Component cp in currentObject[index].GetComponentsInChildren())
            {
                if (Component.ReferenceEquals(cp, cp.GetComponent()) || Component.ReferenceEquals(cp, cp.GetComponent()) || Component.ReferenceEquals(cp, cp.GetComponent()))
                {

                }
                else
                {
                    Undo.DestroyObjectImmediate(cp);
                }
            }
        }
    }
}

Selection类是编辑器类,使用需要using UnitryEditor;且脚本要放在Editor文件夹。

你可能感兴趣的:(unity,unity3d)