Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Enemy waves

Discussion in 'Scripting' started by Rutenis, Aug 10, 2014.

  1. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Hey, so i was wondering, how can i make the enemys to spawn in waves? Because all i have now is that they spawn every 4 seconds. So how can i make it so, if there spawned 10 enemys and they would stop spawnging if i didnt kill those 10. Im decent in scripting, but im having trouble with this one. Basically, i dont know how to say in script, if they are all dead.

    Sorry for bad English.

    -Thanks! :)
     
  2. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    I would handle this by having an EnemyManager or something that spawns all enemies, then tracks to see if they are dead.

    This is example code. Not sure how you are placing enemies or starting waves, but you can see how we track enemies.
    Code (csharp):
    1. public class EnemyManager : MonoBehaviour
    2. {
    3.   public Enemy enemyPrefab;
    4.  
    5.   void Awake()
    6.   {
    7.     activeEnemies = new List<Enemy>();
    8.   }
    9.  
    10.   public void StartWave()
    11.   {
    12.     // Example.
    13.     const int waveSize = 10;
    14.     for (int n = 0; n < waveSize; n++)
    15.     {
    16.       Enemy newEnemy = Instantiate(enemyPrefab) as Enemy;
    17.       newEnemy.Init(HandleDeathCallback);
    18.       activeEnemies.Add(newEnemy);
    19.     }
    20.   }
    21.  
    22.   void HandleDeathCallback(Enemy deadEnemy)
    23.   {
    24.     if (!activeEnemies.Contains(deadEnemy))
    25.       Debug.LogWarning("Could not find enemy!");
    26.     else
    27.     {
    28.       activeEnemies.Remove(deadEnemy);
    29.       Destroy(deadEnemy.gameObject);
    30.     }
    31.     if (activeEnemies.Count <= 0)
    32.       Debug.Log("Wave complete!")
    33.   }
    34.  
    35.   List<Enemy> activeEnemies { get; set; }
    36. }
    Code (csharp):
    1. public class Enemy : MonoBehaviour
    2. {
    3.   public delegate void DeathDelegate(Enemy deadEnemy);
    4.  
    5.   public void Init(DeathDelegate deathCallback)
    6.   {
    7.     this.deathCallback = deathCallback;
    8.   }
    9.  
    10.   /// Called whenever you determine the enemy is dead.
    11.   void OnDeath()
    12.   {
    13.     if (deathCallback != null) deathCallback(this);
    14.   }
    15. }
     
    Last edited: Aug 10, 2014
    Rutenis likes this.
  3. Rutenis

    Rutenis

    Joined:
    Aug 7, 2013
    Posts:
    297
    Thanks! I will check this out! :)