Spawn-Manager with Waves and Random spawnpoint

im new and try to make my project from beginning.

I made A random Spawn position, a IEnumerator to wait between waves. The problems are:

  • Enemys (10) spawn at the same point

  • After waveNum increase, the enemy count dont reset

  • It dont spawn new Enemys

void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        Spawn();
    }

    void Update()
    {
        enemyCount = FindObjectsOfType<Enemy>().Length;
        WaitAndSpawn();
    }

*this code generate random spawn position for enemys:

private Vector3 GenerateSpawnPos(){

 float spawnPosX = Random.Range(-spawnRange, spawnRange);
 float spawnPosZ = Random.Range(-spawnRange, spawnRange);

 Vector3 spawnPos = new Vector3(spawnPosX, 0.91f, spawnPosZ);

 return spawnPos;}

*This is IEnumerator:

private IEnumerator WaitAndSpawn() {

 yield return new WaitForSeconds(waitTime);
 Spawn();}

*And the last Spawn:

private void Spawn(){

 int index = Random.Range(0, enemys.Length);
 Vector3 enemySpawn = GenerateSpawnPos();
 while (Vector3.Distance(player.position, enemySpawn) < treshhold)
 {
    enemySpawn = GenerateSpawnPos();
 }
 for (; enemyCount > 0; enemyCount--)
 {
    Instantiate(enemys[index], enemySpawn, enemys[index].transform.rotation);
 }
 if (enemyCount == 0)
 {
    enemyCount = 10;
    waveNumber++;
 }
 }

My goal is to spawn enemys at random location + outside the radius of player (*4) and spawn timer should be 10 seconds between waves. *for test i made 2.

First thing I notice is you have WaitAndSpawn as a coroutine, but you aren’t calling it properly. Make sure you look into coroutines and how they should be called. (hint, StartCoroutine)

Next, you’re calling it from Update, which is a bad move since it would start it every single frame. Sure, you have a wait in there, but you’ll end up with so many WaitAndSpawn waiting for their yields to end just so they will call Spawn.

Chances are good that this is creating issues for you. You might want a bool instead that gets set so WaitAndSpawn doesn’t queue up a call per frame. Or better yet, probably don’t call it from Update.

1 Like

okay I made it by my self

void SpawnEnemyWave(int enemysToSpawn)
    {
        int index = Random.Range(0, enemys.Length);
      
        for (int i = 0; i < enemysToSpawn; i++)
        {
            Instantiate(enemys[index], GenerateSpawnPos(), enemys[index].transform.rotation);
        }
    }

I changed whole Spawn

and placed some in Update methode :smile: works fine !:wink:

Thx for notice;)