- Home /
How to load prefabs into array
Hi guys
I was just wondering how I would load an array of prefabs using the resources folder ? Resources.load
I want to do this in C#
I know I would porbably use. public GameObject[] item; But how would I load the resources into an array and name them from item0 to how ever many items I have ? Eg. Item0, item1, item2,
Note you don't have to use Resources.Load(). You can put them anywhere in Assets and then drag and drop them on the array positions in the inspector.
Answer by Henrik Poulsen · Feb 24, 2013 at 10:44 AM
There's a couple of ways to do this. The easiest would most likely be:
public GameObject[] items;
void Start()
{
// If you store all your items that you want to load in the same folder (Assets/Resources/MyItemsToLoad).
items = Resources.LoadAll("MyItemsToLoad") as GameObject[];
}
Then it would load all files in that folder. If you keep it to just the items that you want to load and nothing else then it would work nicely.
But if you don't want to do it like this you could do a looping solution instead.
using System.Collections.Generic;
public List<GameObject> items = new List<GameObject>();
void Start()
{
GameObject obj = null;
int counter = 0;
bool done = false;
while(!done)
{
// We just keep loading until obj becomes null
obj = Resources.Load("Item" + counter) as GameObject;
if(obj == null)
done = true; // Let's stop this now.
else
items.Add(obj);
++counter;
}
}
I would prefer the first solution, since I don't like to rely on errors (couldn't load) to know when you are done, but that's a matter of taste and what best suits your situation.
Is the Resources.Load recursive? I have other GameObjects inside child folders that I want the script to add too.
Answer by BootySmashDeluxe · May 05 at 09:10 PM
Here is an example of code that did work for me.
private GameObject[] clouds;
clouds = Resources.LoadAll<GameObject>("Prefabs/Clouds");
Just make sure you have the gameobjects in Assets/Resources/foldername
ie Assets/Resources/Prefabs/Clouds