I’m new to unity, and my C# skills are a little rusty. I’m trying to make a spawner to spit out a random prefab from a list of preabs every 2.5 seconds. I made my empty spawner object but i seem to be stuck on the list part of it. Most of the posts i have found are in java and i’m not 100% sure how to set this up in C#. Any help would be great.
float SpawnTime = 2.5;
List<GameObject> prefabList = new List<GameObject>();
public GameObject Prefab1;
public GameObject Prefab2;
public GameObject Prefab3;
void Start()
{
prefabList.Add(Prefab1);
prefabList.Add(Prefab2);
prefabList.Add(Prefab3);
int prefabIndex = UnityEngine.Random.Range(0,3);
Instantiate(prefabList[prefabIndex]);
}
void Update()
{
}
}
Well, you look like you’re on the right track with your instantiation code, but you missed a couple of spots here and there:
// C# floats have a trailing 'f', or else it's a double
float SpawnTime = 2.5f;
public List<GameObject> prefabList;
// you don't need a GameObject reference for each item.
// Make that list public, and unity will serialize it, so you can fill
// it up in the inspector panel (arrays also work).
// at start, just call a coroutine that will run an endless loop,
// spawning a randomly chosen item every so many seconds.
void Start()
{
StartCoroutine(SpawnRandom());
}
IEnumerator SpawnRandom()
{
// this loop will run infinitely while the game object or component
// is enabled in the scene, yielding for the given amount of time between each iteration
while(this.enabled)
{
yield return new WaitForSeconds(SpawnTime);
Instantiate(prefabList[Random.Range(0,prefabList.Count)]);
}
}
}
Hope this helps.
Cheers