How to create a condition for my coroutine

Hi, it’s your first post, but please look around and try using code tags , because it makes the code formatted and much easier to read.

using System.Collections.Generic;
using UnityEngine;

public class EnemySpawner : MonoBehaviour {

  [SerializeField] GameObject _prefab;
  [SerializeField] float _timeInterval = 10f;
  [SerializeField] [Min(1)] int _enemiesToSpawn = 3;

  int _enemyCount;
  List<GameObject> _enemies;

  void Start() {
    _enemyCount = 0;
    _enemies = new List<GameObject>();
    StartCoroutine(spawnEnemies);
  }

  void Update() {
    if(_enemyCount == _enemiesToSpawn) {
      StopCoroutine(spawnEnemies);
      printList(_enemies);
      enabled = false;
    }
  }

  IEnumerator spawnEnemies() {
    while(_enemyCount < _enemiesToSpawn)
      yield return new WaitForSeconds(_timeInterval);
      if(trySpawnNewEnemy(_prefab)) _enemyCount++;
    }
  }

  bool trySpawnNewEnemy(GameObject prefab) {
    var newEnemy = Instantiate(prefab, new Vector3(Random.Range(2f, 6f), Random.Range(7f, 11f), 0), Quaternion.identity);
    _enemies.Add(newEnemy);
    return true; // true for success, could fail for some reason not covered here
  }

  void printList<T>(IList<T> list) where T : UnityEngine.Object {
    for(int i = 0; i < list.Count; i++) {
      Debug.Log(list[i].name);
    }
  }

}

Something like that.
Some of this code is just decorational / illustrational (namely Update and printList).

edit:
added StopCoroutine

1 Like