General question here, code wise, is there any issue doing this and calling a coroutine from itself? Or am I better off with InvokeRepeating… I can always add triggers to stop this coroutine when I need to, and I’ve never really found a need for InvokeRepeating… Thoughts? Reasons to do this or not to do this? Or any good logic as to why I should abandon this in favor of InvokeRepeating?
IEnumerator SpawnEnemies()
{
yield return new WaitForSeconds(enemySpawnDelay);
int ch = (int)helpers.RandomBetween(0, EnemyFabs.Length);
GameObject g = GameObject.Instantiate(EnemyFabs[ch]);
StartCoroutine(SpawnEnemies());
}
Forget about InvokeRepeating. It’s useful for quick prototyping but should not be used in production. Having a function referenced by a string… What an horrible practice…
While having a coroutine calling itself is technically possible, it’s not advised. It produces garbage, and no one likes garbage, especially the lazy garbage collector
Your couroutine could be written as follow :
IEnumerator SpawnEnemies()
{
// Cache the WaitForSeconds for better performances!
// Unless the wait duration must change between two spawns
WaitForSeconds wait = new WaitForSeconds(enemySpawnDelay);
// I suppose `spawnEnnemies` is a Boolean
// You can set to ` false if you want to control when
// The coroutine must stop.
// You can use `while( true )` + StopCoroutine if you want
while( spawnEnnemies )
{
yield return wait;
int ch = (int)helpers.RandomBetween(0, EnemyFabs.Length);
GameObject g = GameObject.Instantiate(EnemyFabs[ch]);
}
}
Appreciate the info guys, was more curiosity than anything, been programming since the timex sinclair 1000 as a hobbyist, and it never hurts to ask! I especially didnt know about caching the Wait, and @Bunny83 , I will take a look at your CoroutineHelper! Thanks all!