如何从 Assets 文件夹中获取所有预制件?在编辑器中获取无效的强制转换异常

Dan*_*Lip 5 c# unity-game-engine

GameObject[] prefabs = (GameObject[])Resources.LoadAll("Assets/Animations/Test");
Run Code Online (Sandbox Code Playgroud)

主要目标是获取所有预制件,并递归以防Test.

Wus*_*szt 10

Resources.LoadAll 正在资源文件夹中查找。如果您想在资产中查找某些内容,您应该使用 AssetDatabase.FindAssets。

AssetDatabase.FindAssets("t:prefab", new string[] {"Assets/Animations/Test"});
Run Code Online (Sandbox Code Playgroud)

如果您想过滤掉其他资产,您还应该查看其文档。


Wap*_*ull 8

对于 Unity 编辑器端代码,自动执行某些编辑器脚本。它可能是这样的:

string[] guids = AssetDatabase.FindAssets( "t:Prefab" );

foreach( var guid in guids )
{
    var path = AssetDatabase.GUIDToAssetPath( guid );
    GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>( path );

    // For example: searching for broken prefab 
    // recursively go through all Transform(s) and check 
    // name.Contains( "Missing Prefab" )

    // Or maybe find certain type of script using GetComponent API family
    // Or maybe find a missing (broken) MonoBehaviour script using GameObjectUtility.GetMonoBehavioursWithMissingScriptCount
    // etc
Run Code Online (Sandbox Code Playgroud)

用于编辑和修改

请注意,像上面的方法一样迭代预制件有利于读取,但不利于保存,您将不得不经历另一个循环来使其变脏、保存并刷新到磁盘等。

直接编辑“源资源”预制件的一种方法是使用 PrefabUtility API。

对于 2020.1+ 请参阅https://docs.unity3d.com/2020.1/Documentation/ScriptReference/PrefabUtility.EditPrefabContentsScope.html

对于较旧的请参阅https://forum.unity.com/threads/how-do-i-edit-prefabs-from-scripts.685711/ (解决方案位于中间位置)


Oen*_*n44 2

Assets/Resources中创建目录Animations/Test

GameObject[] prefabs = Resources.LoadAll<GameObject>("Animations/Test");
Run Code Online (Sandbox Code Playgroud)

它将获取Test及其子文件夹中所有GameObject类型的文件。