0
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 1 year has passed since last update.

【Unity】任意のPrefabからコンポーネントを全て外す

Last updated at Posted at 2023-10-05

概要

私のプロジェクトでは、基本的に 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のコンポーネントは外さないようにしています。

0
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
0
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?