Why is IEnumerator causing my game to crash immediately?

IEnumerator WaitToSpawn(int delay){

         for (enemiesOnScreen = 0; enemiesOnScreen < maxEnemies; enemiesOnScreen++)
         {
             Instantiate(gameObject, GameObject.Find("Spawn").transform);
         }
     yield return new WaitForSeconds(delay);
 }
 void Start () {
     player = GameObject.Find("VikingPlayer").GetComponent<Movement>();
     StartCoroutine(WaitToSpawn(5));
 }

The second I start the game after this happens, the game crashes. I imagine it’s because it starts instantiating infinitely or something? I’m not sure why this is happening or what I did wrong with the IEnumerator pls help.

What is your intent with Instantiate(gameObject, GameObject.Find("Spawn").transform);? Unless you have a different gameObject variable, that is using the gameObject variable from MonoBehaviour, which is the GameObject the script is on. That object is already instantiated so I do not think you can instantiate it again.

Unity may just copy the GameObject - if it does that, then yes, you are getting an infinite loop of instatiations. Instantiate will clone the GameObject, Start is called on that GameObject, which clones itself, and so on.

What you likely intend to do is have this act as some kind of spawning script. Add a variable to this script to represent the enemy prefeb: public GameObject EnemyPrefab. Then use this script to spawn those prefabs by simply changing that Instantiate line to Instantiate(EnemyPrefab, GameObject.Find("Spawn").transform);.

The spawning script needs to be separate from the Enemy prefab.