概要
私のプロジェクトでは、基本的に Editor からの AddComponent は禁止しています。基本的には、[RequireComponent(typeof(HogeModule))] を使って、AddComponent するようにしています。すると、古いPrefabからComponentを一掃したいというニーズが生まれました。ということで実装。
コード
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HiArda
{
public class RemoveAllComponents : EditorWindow
{
#if UNITY_EDITOR
[MenuItem("Assets/Remove All Components")]
public static void DoRemoveAllComponents()
{
GameObject[] selectedObjects = Selection.gameObjects;
foreach (GameObject selectedObject in selectedObjects)
{
PrefabAssetType prefabType = PrefabUtility.GetPrefabAssetType(selectedObject);
if (prefabType == PrefabAssetType.Regular || prefabType == PrefabAssetType.Variant)
{
string path = AssetDatabase.GetAssetPath(selectedObject);
GameObject originalPrefab = PrefabUtility.LoadPrefabContents(path);
Component[] components = originalPrefab.GetComponents<Component>();
foreach (Component component in components)
{
if (component is Transform) continue;
if (component is Animator) continue;
DestroyImmediate(component, true);
}
PrefabUtility.SaveAsPrefabAsset(originalPrefab, path);
PrefabUtility.UnloadPrefabContents(originalPrefab);
Debug.Log("[RemoveAllComponent] Success. paht=" + path);
}
else
{
Debug.Log("[RemoveAllComponent] Please select a Prefab to remove components from.");
}
}
}
#endif
}
}
使い方
任意のPrefabをProjectWindowから右クリックして、Remove All Components を押下します。
注意点
ここでは、Animatorのコンポーネントは外さないようにしています。