Hey, I have a question regarding this script.
I have watched this tutorial several times but I can’t detect the error. Can someone help me?
The script is spawning 2 Enemies like i said it should do, but its not detecting if delete these Enemies.
I appreciate any answer. Thanks in advance!
Finn
Part 1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaveSpawner : MonoBehaviour {
public enum SpawnState { Spawning, Waiting, Counting } // state of the Wave
[System.Serializable]
public class Wave
{
public string name; //wave name: Easy
public Transform enemy; //Which Prefab should be spawned: Enemy
public int count; //how much Enemys should be spawned per wave: 6
public float rate; //how often the count of enemies should spawn
}
public Wave[] waves;
private int nextWave = 0;
public float timeBetweenWaves = 5f; //Time between waves: 5f = 5seconds
public float waveCountdown; //time Counting down to next wave: 3... 2... 1...
private float searchCountdown = 1f; // how long to search for alive enemies
private SpawnState state = SpawnState.Counting;
void Start()
{
waveCountdown = timeBetweenWaves;
}
void Update()
{
if (state == SpawnState.Waiting) //starts method to check if enemies are still alive
{
searchCountdown = 1f; //search countdown 1s
if (!EnemyIsAlive())
{
//begin a new Wave
Debug.Log("Wave Completed!");
return;
}
else
{
return;
}
}
if (waveCountdown <= 0) //ask if ready for new Wave
{
if (state != SpawnState.Spawning) //ask if Waves are already spawning
{
StartCoroutine( SpawnWave ( waves[nextWave] ) ); //start Spawning Routine
}
}
else
{
waveCountdown -= Time.deltaTime; //if not count down
}
}
bool EnemyIsAlive() //method to search for living enemies
{
searchCountdown -= Time.deltaTime; //count down search time
if (searchCountdown <= 0f) //if search countdown = 0
{
if (GameObject.FindGameObjectWithTag("Enemy") == null) //check if enemy is alive
{
return false; //enemies arent allive
}
}
return true; // enemies are allive
}
IEnumerator SpawnWave (Wave _wave) //Spawning Routine
{
Debug.Log("Spawning Wave: " + _wave.name);
state = SpawnState.Spawning; //State: Spawning
for (int i = 0; i < _wave.count; i++) //loop through amount of enemy
{
SpawnEnemy(_wave.enemy); //spawn enemy Method
yield return new WaitForSeconds(1f / _wave.rate); //time between spawning of each enemy
}
state = SpawnState.Waiting; //State: Waiting
yield break; //stop
}
void SpawnEnemy (Transform _enemy) //spawn enemy Method
{
Debug.Log("Spawning Enemy: " + _enemy.name);
Instantiate(_enemy, transform.position, transform.rotation);
}
}