请写一段unity editor代码,找到所有带有某个脚本的预制体
时间: 2024-03-17 15:41:09 浏览: 90
以下是一段Unity Editor代码,可以找到所有带有指定脚本的预制体。您可以将此脚本附加到Editor文件夹中的任何脚本中,然后在Unity编辑器中单击该脚本的“查找预制体”按钮,以查找所有带有该脚本的预制体:
```c#
using UnityEngine;
using UnityEditor;
public class FindPrefabsWithScript : EditorWindow
{
private MonoScript targetScript;
private GameObject[] prefabList;
private Vector2 scrollPosition;
[MenuItem("Window/Find Prefabs With Script")]
public static void ShowWindow()
{
GetWindow<FindPrefabsWithScript>("Find Prefabs With Script");
}
private void OnGUI()
{
EditorGUILayout.HelpBox("Select a script to find all prefabs that contain it.", MessageType.Info);
targetScript = EditorGUILayout.ObjectField("Target Script", targetScript, typeof(MonoScript), false) as MonoScript;
GUI.enabled = targetScript != null;
if (GUILayout.Button("Find Prefabs"))
{
FindPrefabs();
}
GUI.enabled = true;
if (prefabList != null)
{
EditorGUILayout.LabelField("Prefabs Found: " + prefabList.Length);
if (prefabList.Length > 0)
{
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
foreach (GameObject prefab in prefabList)
{
EditorGUILayout.ObjectField(prefab, typeof(GameObject), false);
}
EditorGUILayout.EndScrollView();
}
}
}
private void FindPrefabs()
{
string[] guids = AssetDatabase.FindAssets("t:Prefab");
prefabList = new GameObject[0];
foreach (string guid in guids)
{
string assetPath = AssetDatabase.GUIDToAssetPath(guid);
GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(GameObject)) as GameObject;
if (asset != null && PrefabUtility.GetPrefabAssetType(asset) == PrefabAssetType.Regular)
{
Component[] components = asset.GetComponentsInChildren<Component>(true);
foreach (Component component in components)
{
if (component.GetType() == targetScript.GetClass())
{
ArrayUtility.Add(ref prefabList, asset);
break;
}
}
}
}
Repaint();
}
}
```
该脚本将创建一个新的窗口,您可以在其中选择要查找的脚本。单击“Find Prefabs”按钮后,它将搜索所有预制体,找到带有指定脚本的所有预制体,并将它们列出在窗口中。
阅读全文