Many loops to instantiate different prefabs during a given time
Hello, I'm returning to game development studies using Unity, I believe the answer to my question is something simple, but I tried and researched a lot without progress.
I'm trying to create a process to randomly instantiate prefabs that are in an array. For now there are only three levels, each lasts 10 seconds and has different prefabs to be instantiated.
I was able to do this using the Inumerator, however for each level i need to create a new loop. Here's the script:
private float _levelOneTime = 10f;
private float _levelTwoTime = 20f;
private float _levelThreeTime = 30f;
public GameObject[] _levelPrefabs;
private Coroutine _spawnerCoroutine;
void Start()
{
_spawnerCoroutine = StartCoroutine(Spawner());
}
// Here where the magic happens, I had to use three loops for three different instances.
IEnumerator Spawner()
{
while (Time.timeSinceLevelLoad <= _levelOneTime)
{
int randomPrefab = Random.Range(0, 2);
Instantiate(_levelPrefabs[randomPrefab], new Vector3(0, 0, 10), Quaternion.identity);
yield return new WaitForSeconds(5);
}
while (Time.timeSinceLevelLoad > _levelOneTime && Time.timeSinceLevelLoad <= _levelTwoTime)
{
int randomPrefab = Random.Range(3, 5);
Instantiate(_levelPrefabs[randomPrefab], new Vector3(0, 0, 10), Quaternion.identity);
yield return new WaitForSeconds(5);
}
while (Time.timeSinceLevelLoad > _levelTwoTime && Time.timeSinceLevelLoad <= _levelThreeTime)
{
int randomPrefab = Random.Range(6, 9);
Instantiate(_levelPrefabs[randomPrefab], new Vector3(0, 0, 10), Quaternion.identity);
yield return new WaitForSeconds(5);
}
}
I know this will make the script very long if i want to create more levels.
I would like to know if there is a way to instantiate prefabs within the time of their respective levels without having to use the while repetition system so often. ||| Thank you for your attention and patience.
Your answer
Follow this Question
Related Questions
Error Instantiating Prefab in while look at end of row, Happens after a random amount of rows 0 Answers
Need Help instantiating a Game Object Prefab. 0 Answers
How to instantiate UI elements centered around an empty object 1 Answer
I need help with Instantiate,I need help instantiating blocks! 0 Answers
I want to make make a plant to grow after few seconds. 0 Answers