Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Jason991 · Nov 14, 2013 at 10:13 AM · c#tower-defensespawner

How to spawn enemy wave by wave?

Hi guys, i have implemented Corrupter heart's enemy spawner successfully but unfortunely i do not know how to make it to spawn the creep wave by wave and level by level means wave 2 spawn medium, wave 3 spawn hard and so on. Below is the script

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Spawner : MonoBehaviour {
 
        
  
     public Transform destination = null;
 
     // Color of the gizmo
     public Color gizmoColor = Color.red;
  
     //-----------------------------------
     // All the Enums
     //-----------------------------------
     // Spawn types
     public enum SpawnTypes
     {
         Normal,
         Once,
         Wave,
         TimedWave
     }
     // The different Enemy levels
     public enum EnemyLevels
     {
         Easy,
         Medium,
         Hard,
         Boss
     }
     //---------------------------------
     // End of the Enums
     //---------------------------------
  
     // Enemy level to be spawnedEnemy
     public EnemyLevels enemyLevel = EnemyLevels.Easy;
  
     //----------------------------------
     // Enemy Prefabs
     //----------------------------------
     public GameObject EasyEnemy;
     public GameObject MediumEnemy;
     public GameObject HardEnemy;
     public GameObject BossEnemy;
     private Dictionary<EnemyLevels, GameObject> Enemies = new Dictionary<EnemyLevels, GameObject>(4);
     //----------------------------------
     // End of Enemy Prefabs
     //----------------------------------
  
     //----------------------------------
     // Enemies and how many have been created and how many are to be created
     //----------------------------------
     public int totalEnemy = 10;
     private int numEnemy = 0;
     private int spawnedEnemy = 0;
     //----------------------------------
     // End of Enemy Settings
     //----------------------------------
  
  
     // The ID of the spawner
     private int SpawnID;
  
     //----------------------------------
     // Different Spawn states and ways of doing them
     //----------------------------------
     private bool waveSpawn = false;
     public bool Spawn = true;
     public SpawnTypes spawnType = SpawnTypes.Normal;
     // timed wave controls
     public float waveTimer = 30.0f;
     private float timeTillWave = 0.0f;
     //Wave controls
     public int totalWaves = 5;
     private int numWaves = 0;
     //----------------------------------
     // End of Different Spawn states and ways of doing them
     //----------------------------------
     void Start()
     {
         // sets a random number for the id of the spawner
         SpawnID = Random.Range(1, 500);
         Enemies.Add(EnemyLevels.Easy, EasyEnemy);
         Enemies.Add(EnemyLevels.Boss, BossEnemy);
         Enemies.Add(EnemyLevels.Medium, MediumEnemy);
         Enemies.Add(EnemyLevels.Hard, HardEnemy);
     }
     // Draws a cube to show where the spawn point is... Useful if you don't have a object that show the spawn point
     void OnDrawGizmos()
     {
         // Sets the color to red
         Gizmos.color = gizmoColor;
         //draws a small cube at the location of the gam object that the script is attached to
         Gizmos.DrawCube(transform.position, new Vector3 (0.5f,0.5f,0.5f));
     }
     void Update ()
     {
         if(Spawn)
         {
             // Spawns enemies everytime one dies
             if (spawnType == SpawnTypes.Normal)
             {
                 // checks to see if the number of spawned enemies is less than the max num of enemies
                 if(numEnemy < totalEnemy)
                 {
                     // spawns an enemy
                     spawnEnemy();
                 }
             }
             // Spawns enemies only once
             else if (spawnType == SpawnTypes.Once)
             {
                 // checks to see if the overall spawned num of enemies is more or equal to the total to be spawned
                 if(spawnedEnemy >= totalEnemy)
                 {
                     //sets the spawner to false
                     Spawn = false;
                 }
                 else
                 {
                     // spawns an enemy
                     spawnEnemy();
                 }
             }
             //spawns enemies in waves, so once all are dead, spawns more
             else if (spawnType == SpawnTypes.Wave)
             {
                 if(numWaves < totalWaves + 1)
                 {
                     if (waveSpawn)
                     {
                         //spawns an enemy
                         spawnEnemy();
                     }
                     if (numEnemy == 0)
                     {
                         // enables the wave spawner
                         waveSpawn = true;
                         //increase the number of waves
                         numWaves++;
                     }
                     if(numEnemy == totalEnemy)
                     {
                         // disables the wave spawner
                         waveSpawn = false;
                     }
                 }
             }
             // Spawns enemies in waves but based on time.
             else if(spawnType == SpawnTypes.TimedWave)
             {
                 // checks if the number of waves is bigger than the total waves
                 if(numWaves <= totalWaves)
                 {
                     // Increases the timer to allow the timed waves to work
                     timeTillWave += Time.deltaTime;
                     if (waveSpawn)
                     {
                         //spawns an enemy
                         spawnEnemy();
                     }
                     // checks if the time is equal to the time required for a new wave
                     if (timeTillWave >= waveTimer)
                     {
                         // enables the wave spawner
                         waveSpawn = true;
                         // sets the time back to zero
                         timeTillWave = 0.0f;
                         // increases the number of waves
                         numWaves++;
                         // A hack to get it to spawn the same number of enemies regardless of how many have been killed
                         numEnemy = 0;
                     }
                     if(numEnemy >= totalEnemy)
                     {
                         // diables the wave spawner
                         waveSpawn = false;
                     }
                 }
                 else
                 {
                     Spawn = false;
                 }
             }
         }
     }          
     // spawns an enemy based on the enemy level that you selected
     private void spawnEnemy()
     {
         GameObject Enemy = (GameObject) Instantiate(Enemies[enemyLevel], gameObject.transform.position, Quaternion.identity);
         NavMeshAgent n = Enemy.GetComponent<NavMeshAgent>();
         n.destination = destination.position;
         Enemy.SendMessage("setName", SpawnID);
         // Increase the total number of enemies spawned and the number of spawned enemies
         numEnemy++;
         spawnedEnemy++;
         
     }
     // Call this function from the enemy when it "dies" to remove an enemy count
     public void killEnemy(int sID)
     {
         // if the enemy's spawnId is equal to this spawnersID then remove an enemy count
         if (SpawnID == sID)
         {
             numEnemy--;
         }
     }
     //enable the spawner based on spawnerID
     public void enableSpawner(int sID)
     {
         if (SpawnID == sID)
         {
             Spawn = true;
         }
     }
     //disable the spawner based on spawnerID
     public void disableSpawner(int sID)
     {
         if(SpawnID == sID)
         {
             Spawn = false;
         }
     }
     // returns the Time Till the Next Wave, for a interface, ect.
     public float TimeTillWave
     {
         get
         {
             return timeTillWave;
         }
     }
     // Enable the spawner, useful for trigger events because you don't know the spawner's ID.
     public void enableTrigger()
     {
         Spawn = true;
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by felixpk · Nov 14, 2013 at 02:08 PM

Look at this, I made a fully functionable enemySpawner wave by wave, just wanted to share it with you ;) All is working fine, just the setDifficulty part is not implementet yet.

Hope it helps ;)

     public GameObject enemy;
     
     private bool waveActive = false;
     
     public Transform[] spawnPointRoot;
     
     private int waveLevel = 0;
     private float diffucultyMultiplier = 1.0f;
     private float intermissionLength = 10f;
     private int enemyCount = 0;
     private ArrayList enemies;
     private bool allEnemiesSpawned = false;
     
     private float velocity = 4f;
     private float health = 20f;
     private int enemyAmount = 10;
     private float spawnIntervall = 2;
     
     private GUIScript gui;
     
     public enum GameState {
         preStart,
         activeWave,
         intermission
     }
     
     GameState state = GameState.preStart;
     
     void Start(){
         enemies = new ArrayList();
         gui = Camera.main.GetComponentInChildren<GUIScript>();
     }
     
     void Update () {
         switch(state){
             
             case GameState.preStart:
                 if(gui.startWave){
                     setNextWave();
                     startNewWave();
                     gui.startWave = false;
                 }else {
                     
                 }
             break;
             
             case GameState.activeWave:
                 if(enemyCount == 0 && waveActive && allEnemiesSpawned){
                     finishWave();
                 }
             break;
             
             case GameState.intermission:
             break;
         }
     }
     
     void LateUpdate(){
         for(int i = 0; i < enemies.Count; i++){
             if((GameObject)(enemies[i]) == null){
                 enemies.Remove(enemies[i]);
             }
         }
         enemyCount = enemies.Count;
     }
     
     void setNextWave(){
         diffucultyMultiplier = (diffucultyMultiplier * waveLevel) / 2;
     }
     
     void startNewWave(){
         state = GameState.activeWave;
         
         StartCoroutine(StartMission(1.5f));
         
         waveLevel++;
     }
     
     IEnumerator InterMission(float seconds){
         yield return new WaitForSeconds(seconds);
         setNextWave();
         startNewWave();
     }
     
     IEnumerator EnemySpawnerRoutine(float spawnIntervall, int enemyAmount, float velocity, float health){
         for(int i = 0; i < enemyAmount; i++){
             spawnNewEnemy(velocity, health);
             yield return new WaitForSeconds(spawnIntervall);
         }
         allEnemiesSpawned = true;
     }
     
     void finishWave(){
         StartCoroutine("InterMission",intermissionLength);
         state = GameState.intermission;
         waveActive = false;
     }
     
     void spawnNewEnemy(float velocity, float health){
         GameObject e = (GameObject) Instantiate(enemy, new Vector3(0,0,0), Quaternion.identity);
         EnemyScript es = e.GetComponentInChildren<EnemyScript>();
         int i = Random.Range(0,2);
         es.setWaypoints(spawnPointRoot[i]);
         es.maxHealth = health;
         es.currHealth = health;
         es.speed = velocity;
         enemyCount++;
         enemies.Add(e);
     }
     
     IEnumerator StartMission(float seconds){
         yield return new WaitForSeconds(seconds);
         
         allEnemiesSpawned = false;
         
         StartCoroutine(EnemySpawnerRoutine(spawnIntervall,enemyAmount,velocity,health));
         
         waveActive = true;
     }
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Jason991 · Nov 14, 2013 at 05:09 PM 0
Share

Hi bro thanks for your sharing but unfortunately im quite new to unity so couldnt understand much i found another way to solve part of my problem which is

 if (Time.time <= 1.0f) {
             // spawn
             GameObject g = (GameObject)Instantiate(teddy, transform.position, Quaternion.identity);
  
             // get access to the navmesh agent component
             Nav$$anonymous$$eshAgent n = g.GetComponent<Nav$$anonymous$$eshAgent>();
             n.destination = destination.position;
             
  
           
         }
         
         if (timeLeft <= 5.0f && Time.time <=1.0f) {
             // spawn
             GameObject g = (GameObject)Instantiate(teddy2, transform.position, Quaternion.identity);
  
             // get access to the navmesh agent component
             Nav$$anonymous$$eshAgent n = g.GetComponent<Nav$$anonymous$$eshAgent>();
             n.destination = destination.position;

but currently my problem is i spawning thousands of it and non-stop, how do i solve it?

avatar image felixpk · Nov 14, 2013 at 11:55 PM 0
Share

Hey there, no problem, it may be usefull to look at the StartCoroutine things! But anyway, your are checking: if (Time.time

Ins$$anonymous$$d try this:

 if(Time.time >= lastSpawnedEnemy){
  // spawn enemy here
 
 lastSpawnedEnemy = Time.time + spawnintervallTime;
 }

you get the point? Your are checking if Time.time is greater than 1.0f, Time.time will ever be greater than 1.

Hope I could help!

avatar image Jason991 · Nov 16, 2013 at 04:54 AM 0
Share

Hey there thanks alot im able to spawn script by following your method but how do i stop it from spawning continuously? if my intention is just to spawn one time?

avatar image felixpk · Nov 16, 2013 at 06:22 PM 0
Share

You can use for example an int to count the enemys you have spawned.

 void SpawnEnemy(){
  Instatntiate(..);
  enemyCount++;
 }
 
 void spawn$$anonymous$$anager(){
  if(enemyCount <= maxEnemies){
   SpawnEnemy();
  }
 }

Something like that would work. Otherwise look at my code I posted before, especially the party with:

  IEnumerator EnemySpawnerRoutine(float spawnIntervall, int enemyAmount, float velocity, float health){
        for(int i = 0; i < enemyAmount; i++){
          spawnNewEnemy(velocity, health);
          yield return new WaitForSeconds(spawnIntervall);
        }
        allEnemiesSpawned = true;
     }
avatar image le4feo · Apr 04, 2015 at 08:55 PM 0
Share

Can you put a demo on how your enemies wave work?

Show more comments
avatar image
0

Answer by oranmooney · Jul 03, 2017 at 02:54 AM

private GUIScript gui; is not working i have used 'using UnityEngin.UI;' is there anything else i need to add to it?

@felixpk

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How t o make sure the enemy is spawn at specific time? 1 Answer

An OS design issue: File types associated with their appropriate programs 1 Answer

Help with if statement 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges