Files
zumbi-game/Assets/Scripts/ZombieSpawnerLogic.cs
T

55 lines
1.3 KiB
C#

using System.Collections.Generic;
using UnityEngine;
public class ZombieSpawnerLogic : MonoBehaviour
{
public GameObject Prefab;
public byte MinCooldownSeconds = 5;
public byte MaxCooldownSeconds = 30;
public byte MaxSpawns = 5;
private float _currentSpawnDelay;
private float _lastSpawn;
private readonly List<GameObject> _spawns = new();
void Start()
{
_lastSpawn = Time.time;
PickNewSpawnDelay();
}
void FixedUpdate()
{
RemoveDestroyedZombies();
AttemptZombieSpawn();
}
private void PickNewSpawnDelay()
{
_currentSpawnDelay = Random.Range(MinCooldownSeconds, MaxCooldownSeconds);
Debug.Log($"Zombie spawner new spawn delay: {_currentSpawnDelay}s");
}
private void AttemptZombieSpawn()
{
if (Time.time - _lastSpawn < _currentSpawnDelay)
{
return;
}
if (_spawns.Count >= MaxSpawns)
{
Debug.Log("Cannot spawn zombie, capacity reached");
return;
}
Debug.Log("Spawning zombie");
var newZombie = Instantiate(Prefab, transform);
_spawns.Add(newZombie);
_lastSpawn = Time.time;
PickNewSpawnDelay();
}
private void RemoveDestroyedZombies() => _spawns.RemoveAll(zombie => zombie == null);
}