Home > Net >  in TowerDefence Code,for spawning enemies
in TowerDefence Code,for spawning enemies

Time:08-18

i want to spawn multiple enemies in the same enemy wave,maybe some one can help...in new to C#.

thats the code in using now:

public class WaveSpawner_2 : MonoBehaviour
{

public static int EnemiesAlive = 0;

 public Wave2[] waves;
 public Transform spawnPoint;
 public float timeBetweenWaves = 5f;

[SerializeField] TextMeshProUGUI waveCountDownText;

public GameManager gameManager;

       float countDown = 2f;
        
        int waveIndex = 0;

 void Start() 
 {
   EnemiesAlive = 0;  
 }

 private void Update() 
 {
    
    if(EnemiesAlive > 0)
    {
      return;
    }
    
    if (waveIndex == waves.Length)
        {
       gameManager.WinLevel();
         this.enabled = false;
        }
            
    if(countDown <= 0f)
    {
       StartCoroutine(SpawnWave());
       countDown = timeBetweenWaves;
       return;
    }
    
    countDown -= Time.deltaTime;
    countDown = Mathf.Clamp(countDown, 0f, Mathf.Infinity);
    waveCountDownText.text = string.Format("{0:00.00}", countDown);
  }
 
   IEnumerator SpawnWave ()
    {
        PlayerStats.Rounds  ;
      Wave2 wave = waves[waveIndex];
      EnemiesAlive = wave.count;
        for (int i = 0; i < wave.count; i  )
        {
            SpawnEnemy(wave.enemy);
            yield return new WaitForSeconds(1f / wave.rate);
        }
        waveIndex  ;
    }   
    void SpawnEnemy(GameObject enemy)
    {
       Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
       EnemiesAlive  ;
    }
  

}

and thats the second class:

[System.Serializable]
public class Wave2
{
  [Header("DeafultEnemy")]
  public GameObject enemy;
  public int count;
  public float rate;

  
}

ive been looking 2 days for the solution but coiuldnt find one..im new to c# so maybe i did found it but didnt understand it...trying my luck here, thanks.

CodePudding user response:

The simplest way to achieve this goal is to change the GameObject enemy inside of Wave2 to an array.

[Serializable]
public class WaveData
{
    public GameObject[] prefabs;
    public int count;
    public float rate;
}

Then inside of SpawnWave, you can use the prefabs array to get a random prefab, alternate between prefabs, or some other picking algorithm.

for (int i = 0; i < wave.count; i  )
{
    // Getting a random enemy
    var enemyToSpawn = wave.prefabs[Random.Range(0, wave.prefabs.Length)];
    SpawnEnemy(enemyToSpawn);
}

CodePudding user response:

I am not sure what do you mean by spawn multiple enemies at the same wave, For the code it’s look like you spawning enemy every few game ticks, and if so, why for do not calling the SpawnEnemy in look to instantiate multiple enemies?

  • Related