Files
ggj2026/Assets/Scripts/Spawner.cs
T

57 lines
1.4 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;
private readonly List<GameObject> spawned = new List<GameObject>();
void Start()
{
// 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;
}
// Spawn the object at the spawner's position and rotation
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;
}
}