Home > Net >  Unity Spawn-Manager with Waves
Unity Spawn-Manager with Waves

Time:08-30

I'm new and try to make my project from beginning.

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

  1. Enemies (10) spawn at the same point
  2. After waveNum increases, the enemy count doesn't reset
  3. It don't spawn new Enemies

Here's the code to generate random spawn position for enemies:

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 the 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  ;
    }
}

Start and Update 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.

CodePudding user response:

Spawn logic has a couple of problems. You use several loops which has no sense. Spawn logic:

  1. loop x times
  2. inside loop generate position and instantiate

Please see the following code:

  private void Start()
  {
    InvokeRepeating("SpawnWave", 0, 2);
  }

  private void SpawnWave()
  {
    for (int i = 0; i < enemyCount; i  )
    {
      int index = Random.Range(0, enemys.Length);

      Vector3 position = GenerateSpawnPos();

      Instantiate(enemys[index], position, enemys[index].transform.rotation);
    }
  }
  • Related