Files
ggj2026/Assets/Scripts/Spawner.cs
T
2026-01-31 19:44:21 -06:00

84 lines
1.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
// Reference to the Prefab to Spawn
[SerializeField] private GameObject objectToSpawn;
// Time interval between spawns
public float spawnInterval = 1f;
[SerializeField] private int maxAlive = 0;
[SerializeField] private bool spawnOnStart = true;
[SerializeField] private bool repeatSpawns = true;
private readonly List<GameObject> spawned = new List<GameObject>();
private void OnEnable()
{
if (spawnOnStart)
{
SpawnOnce();
}
}
void Start()
{
if (repeatSpawns)
{
// Start the spawning process using a Coroutine
StartCoroutine(SpawnRoutine());
}
}
private IEnumerator SpawnRoutine()
{
// Infinite loop to keep spawning (can be modified)
while (true)
{
// Wait for the specified interval
yield return new WaitForSeconds(spawnInterval);
if (objectToSpawn == null)
{
continue;
}
if (maxAlive > 0 && CountAlive() >= maxAlive)
{
continue;
}
SpawnOnce();
}
}
private void SpawnOnce()
{
if (objectToSpawn == null)
{
return;
}
if (maxAlive > 0 && CountAlive() >= maxAlive)
{
return;
}
var instance = Instantiate(objectToSpawn, transform.position, Quaternion.identity);
spawned.Add(instance);
}
private int CountAlive()
{
for (var i = spawned.Count - 1; i >= 0; i--)
{
if (spawned[i] == null)
{
spawned.RemoveAt(i);
}
}
return spawned.Count;
}
}