Question by
DaresFireson · Apr 07, 2019 at 07:49 PM ·
c#scripting beginnerspawnwaves
[SOLVED]Multiple enemies Wave Spawner
Hi I have the following wave spawner script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class WaveSpawner : MonoBehaviour {
public static int EnemiesAlive = 0;
public Wave[] waves;
public Transform spawnPoint;
public float timeBetweenWaves = 5f;
public float countdown = 2f;
//public float timeBetweenEnemies = 0.5f;
public Text waveCountdownText;
public Text wavesText;
private int waveIndex = 0;
private void Update()
{
if(EnemiesAlive > 0)
{
return;
}
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);
wavesText.text = (waveIndex + 1) + "/" + waves.Length;
}
IEnumerator SpawnWave()
{
//Debug.Log("Wave Incoming");
Wave wave = waves[waveIndex];
for (int i = 0; i < wave.count; i++)
{
SpawnEnemy(wave.enemy);
yield return new WaitForSeconds(1f / wave.rate);
}
waveIndex++;
PlayerStats.Rounds++;
if(waveIndex == waves.Length)
{
Debug.Log("LEVEL WON!");
this.enabled = false;
}
}
void SpawnEnemy(GameObject enemy)
{
Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
EnemiesAlive++;
}
//void DestroyEnemyOnTargetReach()
//{
// Destroy(gameObject);
//}
}
I am trying to make that I can spawn multiple types of enemies in one wave but can't find a solution. I have tried this solution but it didn't work or I could't implement it as it should. Anyone have a solution for me ?
Comment
Best Answer
Answer by DaresFireson · Apr 08, 2019 at 11:20 AM
Wave is a simple class like this:
using UnityEngine;
public class Wave
{
public GameObject enemy;
public int count;
public float rate;
}
====================================
I made like this:
using UnityEngine;
[System.Serializable]
public class EnemyBlueprint {
public GameObject enemy;
public int enemyCount;
public float enemyRate;
}
and changed Wave class to this:
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Wave {
public EnemyBlueprint[] enemyWave;
public int waveCount;
public float waveRate;
}
changed the SpawnWave() to this:
IEnumerator SpawnWave()
{
//Debug.Log("Wave Incoming");
Wave wave = waves[waveIndex];
//EnemyBlueprint eb = enemies[enemyIndex];
for (int a = 0; a < wave.waveCount; a++)
{
yield return new WaitForSeconds(1f / wave.waveRate);
for (int i = 0; i < enemies.enemyCount; i++)
{
SpawnEnemy(enemies.enemy);
yield return new WaitForSeconds(1f / enemies.enemyRate);
}
}
waveIndex++;
PlayerStats.Rounds++;
if (waveIndex == waves.Length)
{
Debug.Log("LEVEL WON!");
this.enabled = false;
}
}
Now I can choose different enemies in a wave but when I start the game, I get null reference exception and no enemy is spawned