- Home /
How can I populate a list of GameObjects from the prefabs folder?
Basically I'm trying to simplify my project to protect my own personal sanity... I have a mega crap ton of different style objects to create, all will be used by one control script at different times. Basically I'm curious if instead of having to drag-and-drop each onto the list in the inspector if I can have it so when the script is Awake it automatically populates the list with ALL the GameObjects in Assets/Prefabs/Cubes...
I searched on Bing quite a bit but came up short on a specific answer... Sorry if it's a repeat question.
Answer by HenryStrattonFW · Jan 10, 2017 at 11:58 PM
The short answer, is no. At runtime (outside of the editor) the concept of the location "Assets/Prefabs/Cubes" simply does not exist.
However there are ways you can still achieve what you want. It still involves having all of your prefabs attached to your object in the inspector, however that doesn't mean you have to do that by hand. You can write and editor script (or just a method on your objects script that is contains in UNITY_EDITOR define check) that scans your folder of choice and searches it for all valid objects that you want (either by type, naming convention, etc). and then it sets the value on your object.
Here is small example of a script where I want to get all texture objects from a specific folder. It was written using Unity 5.5 but I'm fairly sure the asset database calls/filters are the same in most recent versions.
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections.Generic;
public class TextureCollection : MonoBehaviour
{
[SerializeField]
private Texture2D[] m_Textures;
#if UNITY_EDITOR
[ContextMenu("Find Textures")]
private void _FindTextures()
{
List<Texture2D> lTextures = new List<Texture2D>();
string[] lGuids = AssetDatabase.FindAssets("t:Texture2D", new string[] { "Assets/Test" });
for (int i = 0; i < lGuids.Length; i++)
{
string lAssetPath = AssetDatabase.GUIDToAssetPath(lGuids[i]);
lTextures.Add(AssetDatabase.LoadAssetAtPath<Texture2D>(lAssetPath));
}
m_Textures = lTextures.ToArray();
}
#endif
}
Then you save your scene or prefab (depending on your object) and then the objects in question will be included in your build assuming the object with this script on is included as a resource or in a scene, and your main object will have all the references it needs ready to go when it starts up.
Your answer
![](https://koobas.hobune.stream/wayback/20220612104540im_/https://answers.unity.com/themes/thub/images/avi.jpg)