5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity(C#)】Edtitor拡張でコンポーネントを一括削除

Posted at

コンポーネント 一括削除

私がよくやるのは
こいつらRigidbodyやらBoxColliderいらないのに!誰だよつけたの!
ってやつです。

もちろん自分でつけました。

そうでなくとも、Assetに入っているQuadやCubeを大量に組み合わせて作られたオブジェクトなどを利用したい場合、
このコンポーネントいらないな~ってことがあるかと思います。

そんなこんなでコンポーネント一括削除を実装しました。

今回はタイトル通りEdtitor拡張で
ボタンを押したら実行されるというものを作りました。

コード

今回は親オブジェクトにアタッチしたスクリプトが自身の子オブジェクトを確認しに行くという実装で行いました。
なのでScene上に存在する全てのオブジェクトのコンポーネントを一括で削除するというものではありません。

一括削除したいコンポーネントを持つオブジェクトの親にアタッチ
using UnityEngine;
using UnityEditor;

public class RemoveComponentInChild : MonoBehaviour {

    [Header("削除したいコンポーネントを文字列で指定"),SerializeField]
    string componentName;

    //コンポーネントを取得して該当コンポーネントを削除
    void GetComAndDes()
    {
        Component[] components = GetComponentsInChildren<Component>();
        foreach(Component component in components)
        {
            if (component.GetType().Name == componentName)
            {
                DestroyImmediate(component);
            }
        }
    }

# if UNITY_EDITOR
    [CustomEditor(typeof(RemoveComponentInChild))]
    public class ExampleInspector : Editor
    {
        RemoveComponentInChild rootClass;

        private void OnEnable()
        {
            rootClass = target as RemoveComponentInChild;
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            if (GUILayout.Button("一括削除"))
            {
                // 押下時に実行したい処理
                rootClass.GetComAndDes();
            }

            serializedObject.Update();
            serializedObject.ApplyModifiedProperties();
        }
    }
# endif
}

下記の箇所で行っていることは
①子オブジェクトの全てのComponentを取得
②指定した名前と取得した名前が一致しているか判定
③一致していたら削除
になります。

    //コンポーネントを取得して該当コンポーネントを削除
    void GetComAndDes()
    {
        Component[] components = GetComponentsInChildren<Component>();
        foreach(Component component in components)
        {
            if (component.GetType().Name == componentName)
            {
                DestroyImmediate(component);
            }
        }
    }

ちなみに、DestroyはEdtiorModeでは使えないのでDestroyImmediateを使っています。

Inspectorはこうです。
AllDelete.PNG

Shiftで選択して消せばいいじゃん

おっしゃる通りです。

しかし、Shiftの場合、一つでも消去したいコンポーネントを持たないオブジェクトを選択してしまったら消すことができません。

なのでうまく使い分けるといい感じにプログラマーっぽくなってすごくいいと思います(語彙力)。


参考リンク

GameObjectについている全てのコンポーネントを取得する

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?