I have this script which don’t execute after reloading scene from a button but execute when doing the same thing from another button with the same line of code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class WaveSpawner : MonoBehaviour {
public static int EnemiesAlive = 0;
public Wave[] waves;
public Transform[] spawnPoints;
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 Awake()
{
this.enabled = true;
}
private void Start()
{
Debug.Log(waveIndex + " " + waves.Length + " " + this.enabled);
if (spawnPoints.Length == 0)
{
Debug.LogError("No spawn points referenced!");
}
}
private void Update()
{
if(EnemiesAlive > 0)
{
return;
}
if (waveIndex == waves.Length)
{
Debug.Log("LEVEL WON!");
this.enabled = false;
}
if (countdown <= 0f)
{
if(waveIndex == waves.Length)
{
return;
}
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;
// }
//}
IEnumerator SpawnWave()
{
//Debug.Log("Wave Incoming");
Wave wave = waves[waveIndex];
for (int a = 0; a < wave.waveCount; ++a)
{
Transform sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
yield return new WaitForSeconds(1f / wave.waveRate);
for (int i = 0; i < wave.enemyWave.Length; i++)
{
for (int j = 0; j < wave.enemyWave[i].enemyCount; ++j)
{
SpawnEnemy(wave.enemyWave[i].enemy, sp);
yield return new WaitForSeconds(1f / wave.enemyWave[i].enemyRate);
}
}
}
waveIndex++;
PlayerStats.Rounds++;
//if (waveIndex == waves.Length)
//{
// Debug.Log("LEVEL WON!");
// this.enabled = false;
//}
}
void SpawnEnemy(GameObject enemy, Transform _sp)
{
Instantiate(enemy, _sp.position, _sp.rotation);
EnemiesAlive++;
}
//void DestroyEnemyOnTargetReach()
//{
// Destroy(gameObject);
//}
}