Spawning system bugs

I am making a spawning system for a game I’m working on. It works perfectly fine but enemies spawn on top of each other in massive hordes which not only looks awful, but crashes the engine. The system i have is formatted so that the amount of enemies spawning increases as time goes on. Here is the code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AlternateSpawningScript : MonoBehaviour
{
    // Start is called before the first frame update
    public GameObject[] Demons;
    public int time1;
    public int time2;
    public List<int> wave = new List<int>();
    void Start()
    {
        for (int i = 10; i > 1; i -= 1)
        {
            foreach(int e in wave){
                spawningEnemiesInvoke();
                wave.Add(i);
            }
            
        }
    }

    // Update is called once per frame
    private void FixedUpdate() {
    }
    void spawningEnemiesInvoke(){
        Invoke("spawningEnemies", Random.Range(time1, time2));
    }
    void spawningEnemies(){
            Instantiate(Demons[Random.Range(0, Demons.Length)], transform.position, Quaternion.identity);
    }
}

Is your foreach loop supposed to be in a for loop? for (int i = 10; i > 1; i -= 1) makes the foreach loop run 10 times. If this is intentional, I would suggest object pooling as instantiating that many GameObjects would have a serious performance overhead if they’re not being destroyed as quickly as they are instantiated.


The problem you most likely have is that you are spawning all your enemies at the same spawn point, Instantiate(Demons[Random.Range(0, Demons.Length)], transform.position, Quaternion.identity); where transform.position is always the position to instantiate at. This would lead to all sorts of wacky collision errors (with demons being spawned inside of other demons) and other issues, which can be solved by using multiple spawnpoints. You could have an array of spawnpoints and randomly select one every time you Invoke spawningEnemies() as the spawn point, or just randomly create a Vector3, and assign it to the Vector3 position parameter of the Instantiate function. @Wonderpig