# 4. Enemy Spawners
Part of [[Object Pooling and Spawners]]. Back: [[3. Particle and VFX Pools]]. Next: [[5. Collection Pools Tests and Pitfalls]].
> [!warning] Code not compiled in Unity
> `PooledEnemy` and `EnemySpawner` were type-checked against Unity 6000.5.8f1. They have not been play-tested with a real health or AI component.
## 4.1 A cap is a design number
[[Level Up! (Review)]] treats spawn rate as something the player can read. `aliveCap` is that number: the spawner refuses to `Get` another enemy while `CountActive >= aliveCap`. `maxSize` is a *pool* ceiling (how many inactive instances you are willing to keep, and how many overflows you will Destroy). Do not confuse the two. A pool with `maxSize` 16 and an alive cap of 8 will hold up to eight more inactive bodies after a wipe.
Death must `Release`, never `Destroy(gameObject)`. If an existing health script already destroys the enemy, change that one line; leaving both paths in place is a classic double-release (part 5).
## 4.2 PooledEnemy and EnemySpawner
```csharp
using UnityEngine;
/// <summary>
/// Minimal pooled enemy: on "death" it returns to the EnemySpawner pool.
/// Hook this to your real health component instead of Destroy(gameObject).
/// </summary>
public sealed class PooledEnemy : MonoBehaviour
{
[SerializeField] int maxHealth = 3;
EnemySpawner _spawner;
int _health;
bool _inPool = true;
public void AttachToPool(EnemySpawner spawner) => _spawner = spawner;
public void OnSpawned(Vector3 position, Quaternion rotation)
{
_inPool = false;
_health = maxHealth;
transform.SetPositionAndRotation(position, rotation);
}
public void OnDespawned()
{
_inPool = true;
}
public void TakeDamage(int amount)
{
if (_inPool)
return;
_health -= amount;
if (_health <= 0)
_spawner?.Release(this);
}
}
```
```csharp
using UnityEngine;
using UnityEngine.Pool;
/// <summary>
/// Spawns pooled enemies up to a cap. Enemies must call Release when they die
/// instead of Destroying themselves.
/// </summary>
public sealed class EnemySpawner : MonoBehaviour
{
[SerializeField] PooledEnemy prefab;
[SerializeField] Transform poolRoot;
[SerializeField] Transform[] spawnPoints;
[SerializeField] int defaultCapacity = 8;
[SerializeField] int maxSize = 16;
[SerializeField] int aliveCap = 8;
[SerializeField] float spawnInterval = 1.5f;
[SerializeField] bool collectionCheck = true;
ObjectPool<PooledEnemy> _pool;
float _nextSpawn;
public int CountActive => _pool != null ? _pool.CountActive : 0;
void Awake()
{
if (prefab == null)
{
Debug.LogError("EnemySpawner: assign a PooledEnemy prefab.", this);
return;
}
_pool = new ObjectPool<PooledEnemy>(
createFunc: () =>
{
var enemy = Instantiate(prefab, poolRoot);
enemy.AttachToPool(this);
enemy.gameObject.SetActive(false);
return enemy;
},
actionOnGet: enemy => enemy.gameObject.SetActive(true),
actionOnRelease: enemy =>
{
enemy.OnDespawned();
enemy.gameObject.SetActive(false);
if (poolRoot != null)
enemy.transform.SetParent(poolRoot, false);
},
actionOnDestroy: enemy =>
{
if (enemy != null)
Destroy(enemy.gameObject);
},
collectionCheck: collectionCheck,
defaultCapacity: defaultCapacity,
maxSize: maxSize);
}
void Update()
{
if (_pool == null || spawnPoints == null || spawnPoints.Length == 0)
return;
if (CountActive >= aliveCap)
return;
if (Time.time < _nextSpawn)
return;
_nextSpawn = Time.time + spawnInterval;
var point = spawnPoints[Random.Range(0, spawnPoints.Length)];
if (point == null)
return;
var enemy = _pool.Get();
enemy.OnSpawned(point.position, point.rotation);
}
public void Release(PooledEnemy enemy)
{
if (enemy == null || _pool == null)
return;
_pool.Release(enemy);
}
void OnDestroy()
{
_pool?.Dispose();
_pool = null;
}
}
```
Replace `TakeDamage` with a call from your real health component. Reset NavMesh, animator, and aggro in `OnSpawned` / `OnDespawned` the same way part 2 resets `linearVelocity` — a reused enemy that keeps the last chase target is a bug that looks like AI.
`ObjectPool` is not a wave director. If you already have waves in [[Game Balance and Dynamic Difficulty]] or a tactics list in [[Grid and Turn-Based Tactics]], those systems decide *when* to ask the spawner for a body; this class only owns the pool and the live cap.
Next: [[5. Collection Pools Tests and Pitfalls]].