- Home /
Question by
Michael_Hotte · Jun 13, 2016 at 06:04 AM ·
randomspawnprefabs
Spawn A Random Prefab
I'd like to spawn a random prefab from a selection of prefabs, every few seconds. The spawn point for the prefabs will be the same every time. Is there a simple way to do this?
Comment
Answer by Brijs · Jun 13, 2016 at 09:27 AM
Make a list of prefabs then
Write a coroutine like this
public static class IListExtensions
{
private static System.Random random = new System.Random();
public static T RandomElement<T>(this IList<T> list)
{
return list[random.Next(list.Count)];
}
}
IEnumerator RandomPrefabSpawner()
{
GameObject go = prefabList.RandomElement();
//instantiation Code of random gameobject fetched(go)
yield return new WaitForSeconds(waitTime);
}
Answer by Abhiroop-Tandon · Jun 13, 2016 at 09:08 AM
What you can do is make an array of the prefabs you want to spawn and then choose a random index in the array and use instantiate() to spawn a random prefab !!