- Home /
can you instantiate random prefabs from the resource folder?
im going to be spawning a lot of different prefabs so I want to be able to just drop them in the folder
i just learned how to instantiate from the resource folder
var instance : GameObject = Instantiate(Resources.Load("prefab name"));
now I'm just trying to figure out how I can instantiate random objects from the folder. Is it even possible to instantiate without the name of the object? thanks
maybe i could somehow make an array of the names and then instantiate a random array number? i don't know what i'm doing...
Answer by whydoidoit · Mar 27, 2013 at 02:17 AM
Put the prefabs in a sub folder of resources called "Prefabs" then
var prefabs : Object[] = Resources.LoadAll("Prefabs");
function SpawnRandom() : GameObject
{
var toSpawn : GameObject = prefabs[Random.Range(0, prefabs.Length)];
var spawned = Instantiate(toSpawn);
return spawned;
}
Actually I'd advise that it's better practice to just have a:
var prefabs : GameObject[];
And just assign them in the inspector. Then use that SpawnRandom function - this way you still have a single place to drop them - but go ahead and use Resources if it's a better work flow for you.
Him Tim, can you click the tick next to either Robert's or my answer, depending on which one you choose? It gets us the karma and keeps the board clean.
oh i didnt know how to do that, ok done went back and fixed all my questions, didnt know that was the thing to do
i need load this maps buttons randomly, can u help me?
void LoadMaps ()
{
// Get array of all maps.
TextAsset[] mapNames = Resources.LoadAll<TextAsset>("Maps");
// Create button and set text and onClick event.
foreach(TextAsset map in mapNames)
{
GameObject mapObj = Instantiate(mapButtonPrefab, mapContainer.transform);
mapObj.GetComponentInChildren<Text>().text = map.name;
mapObj.GetComponent<Button>().onClick.AddListener(() => { OnSelectMap(map.name); });
}
}
Answer by robertbu · Mar 27, 2013 at 02:17 AM
If you named them with a number like, "prefab0", "prefab1",..."prefab24", you could do something like:
var name = "prefab"+Random.Range(0, 25);
Then you can instantiate using the generated name. Note Random.Range() of integers is exclusive (does not include) the last value.
If don't want to name them with an order, you can build an array and assign the strings in the inspector.
Note this method will result in duplicates. That is each time you instantiate you will have an equal chance of selecting any string including any that have already been selected.