5
GameObject[] prefabs = (GameObject[])Resources.LoadAll("Assets/Animations/Test");

The main goal is to get all the prefabs and also recursive in case there are sub folders under Test.

3 Answers 3

9

Resourcess.LoadAll is looking for in Resources folder. If you want to find something in assets you should use AssetDatabase.FindAssets.

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

You should also check out its docs if you would like to filter out other assets.

8

For Unity editor-side code, to automate editor script for something. It could be something like this:

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

For editing and modifying

Note that iterating prefab like above method is good for reading but not for saving, you will have to go through another hoops to make it dirty, save, and flush into disk, etc.

One way to edit the "source asset" prefab directly is to use PrefabUtility API.

For 2020.1+ See https://docs.unity3d.com/2020.1/Documentation/ScriptReference/PrefabUtility.EditPrefabContentsScope.html

For older See https://forum.unity.com/threads/how-do-i-edit-prefabs-from-scripts.685711/ (Solution is around mid-post)

2

Create directory Animations/Test inside Assets/Resources.

GameObject[] prefabs = Resources.LoadAll<GameObject>("Animations/Test");

It's going to get all files of type GameObject inside Test and its subfolders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.