3DTD/Assets/Scripts/Manager/EnemySpawnManager.cs

97 lines
2.3 KiB
C#
Raw Normal View History

2024-04-21 05:59:29 +02:00
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
2024-04-21 05:59:29 +02:00
public class EnemySpawnManager : MonoBehaviour
{
public bool HasStarted = false;
public bool IsAutoPlaying = false;
2024-04-21 05:59:29 +02:00
private float time = 0f;
[SerializeField] private LevelDefinition levelDefinition;
[SerializeField] private EnemyCollection enemyCollection;
[SerializeField] private WaypointPath groundPath;
[SerializeField] private WaypointPath skyPath;
[Header("Buttons")]
2024-04-21 06:15:42 +02:00
[SerializeField] private Button PlayButton;
[SerializeField] private Button AutoPlayButton;
2024-04-21 05:59:29 +02:00
private Queue<Wave> waveQueue;
private void Awake()
{
waveQueue = new Queue<Wave>(levelDefinition.Waves);
2024-04-21 06:15:42 +02:00
if (PlayButton != null)
PlayButton.onClick.AddListener(OnPlayButtonClicked);
if (AutoPlayButton != null)
AutoPlayButton.onClick.AddListener(ToggleAutoPlayClicked);
}
2024-04-21 06:15:42 +02:00
public void OnPlayButtonClicked()
{
HasStarted = true;
PopWave();
}
public void ToggleAutoPlayClicked()
{
IsAutoPlaying = !IsAutoPlaying;
2024-04-21 05:59:29 +02:00
}
void Update()
{
if (waveQueue.Count <= 0)
{
return;
}
if (HasStarted && IsAutoPlaying)
time += Time.deltaTime;
2024-04-21 05:59:29 +02:00
if (waveQueue.Peek().spawnTime < time)
{
PopWave();
}
}
void PopWave()
{
2024-04-21 06:45:20 +02:00
time = 0;
2024-04-21 05:59:29 +02:00
Wave spawnWave = waveQueue.Dequeue();
for (int i = 0; i < spawnWave.groups.Length; i++)
{
var group = spawnWave.groups[i];
StartCoroutine(StartSpawnGroup(group));
}
}
IEnumerator StartSpawnGroup(SpawnGroup group)
{
for (int i = 0; i < group.num; i++)
{
EnemyInfo enemyInfo = enemyCollection.Enemies[group.enemyIndex];
GameObject spawned = Instantiate(enemyInfo.prefab);
WaypointEntityData data = new WaypointEntityData(spawned.transform, enemyInfo.moveSpeed);
if (enemyInfo.FlyPath)
{
skyPath.AddObjectToPath(data);
}
else
{
groundPath.AddObjectToPath(data);
}
yield return new WaitForSecondsRealtime(group.spawnInterval);
}
}
}