- Home /
Question by
Brentonk · Mar 16, 2017 at 08:37 PM ·
spawnspawning-enemies
Multiple Enemy Wave Spawners?
I have a working script where at the start my set number of max enemies will Spawn, and upon killing them the next wave starts and spawns the same number of enemies. However when I put in multiple spawners with this script, the enemies only spawn out of one spawner. How can I use this wave spawning system across multiple spawners?
This is my current Wave Spawning Script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemySpawnWaveBased : MonoBehaviour {
public int totalWaves = 5;
private int numWaves = 0;
private bool waveSpawn;
public bool Spawn = true;
public SpawnTypes spawnType = SpawnTypes.Wave;
public int totalEnemy = 10;
public static int numEnemy;
public GameObject Enemy;
void Start () {
}
void Update () {
Debug.Log(waveSpawn);
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
numEnemy = enemies.Length;
if(Spawn)
{
if (spawnType == SpawnTypes.Wave)
{
if(numWaves < totalWaves + 1)
{
if (numEnemy == 0)
{
// enables the wave spawner
waveSpawn = true;
//increase the number of waves
numWaves++;
}
if (waveSpawn)
{
//spawns an enemy
spawnEnemy();
}
if(numEnemy >= totalEnemy)
{
// disables the wave spawner
waveSpawn = false;
}
}
}
}
}
private void spawnEnemy()
{
if (waveSpawn == true) {
Instantiate (Enemy, gameObject.transform.position, Quaternion.identity);
}
}
public enum SpawnTypes
{
Wave
}
}
Comment
are you sure you're putting this script inside that new spawner?
Answer by kuivalappa · Mar 17, 2017 at 02:24 PM
try this spawner
public class Spawner1 : MonoBehaviour {
[System.Serializable]
public class Wave
{
public GameObject enemy;
public int count;
public float rate;
public Transform spawnPoint;
}
public static int EnemiesAlive;
public Wave[] waves;
public static Transform spawnPoint;
public float timeBetweenWaves = 5f;
private float countdown = 2f;
public Text waveCountdownText;
private int waveIndex = 0;
void Update()
{
if (EnemiesAlive > 0)
{
}
if (waveIndex == waves.Length)
{
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()
{
Wave 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)
{
Wave wave = waves[waveIndex];
spawnPoint = wave.spawnPoint;
Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
}
}