-
Notifications
You must be signed in to change notification settings - Fork 0
/
WaveSpawner.cs
139 lines (112 loc) · 3.29 KB
/
WaveSpawner.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
using UnityEngine;
using System.Collections;
public class WaveSpawner : MonoBehaviour {
public enum SpawnState { SPAWNING, WAITING, COUNTING};//defining the data structure
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;//spawn rate
}
public Wave[] waves;
private int nextWave = 0;
public int NextWave
{
get { return nextWave + 1; }
}
public Transform[] spawnPoints;
public float timeBetweenWaves = 5f;
private float waveCountdown;
public float WaveCountdown
{
get { return waveCountdown; }
}
private float searchCountdown = 1f;
private SpawnState state = SpawnState.COUNTING;
public SpawnState State
{
get { return state; }
}
void Start ()
{
if (spawnPoints.Length == 0)
{
Debug.Log("No spawn points referenced.");
}
waveCountdown = timeBetweenWaves;
}
void Update ()
{
if (state == SpawnState.WAITING)//check if player has killed all the enemies. if they are still alive
{
if (!EnemyIsAlive())
{
WaveCompleted();
}
else//if we still have alive enemies
{
return;//let the player kill them before we do it
}
}
if (waveCountdown <= 0)
{
if (state != SpawnState.SPAWNING)
{
StartCoroutine(SpawnWave(waves[nextWave]));
}
}
else
{
waveCountdown -= Time.deltaTime;
}
}
void WaveCompleted()
{
Debug.Log("Wave completed!");
state = SpawnState.COUNTING;
waveCountdown = timeBetweenWaves;
if (nextWave + 1 > waves.Length - 1)
{
nextWave = 0;
Debug.Log("ALL WAVES COMPLETE! Looping...");
}
else
{
nextWave++;
}
}
bool EnemyIsAlive()
{
searchCountdown -= Time.deltaTime;
if (searchCountdown <= 0f)//checking if an enemy is alive only if we actually spawned enemies
{
searchCountdown = 1f;
if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return false;
}
}
return true;
}
IEnumerator SpawnWave(Wave _wave)
{
Debug.Log("Spawing Wave: " + _wave.name);
state = SpawnState.SPAWNING;
//spawn
for (int i = 0; i < _wave.count; i++)//loop through the number of enemies we want to spawn
{
SpawnEnemy(_wave.enemy);//spawn an enemy
yield return new WaitForSeconds(1f/_wave.rate);
}
state = SpawnState.WAITING;//when we are done spawning, we are waiting for the player to kill all the enemies
yield break;
}
void SpawnEnemy(Transform _enemy)
{
Debug.Log("Spawning Enemy:" + _enemy.name);
Transform _sp = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(_enemy, _sp.position, _sp.rotation);
}
}