Source file unity-csharp/arcade-classics/space-invaders/ProjectilePool.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: the Object Pool pattern — reuse bullets instead of Instantiate/Destroy on every shot
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[object-pool-pattern]], [[factory-pattern]]
 
using System.Collections.Generic;
using UnityEngine;
 
// A single pool shared by the player and the invaders. Both sides fire the same
// projectile prefab, parameterised at launch. The Get/Release/SetPool API matches
// the [[object-pool-pattern]] reference page.
public class ProjectilePool : MonoBehaviour
{
    [SerializeField] private Projectile projectilePrefab;
    [SerializeField] private int initialSize = 30;
 
    private readonly Stack<Projectile> inactive = new Stack<Projectile>();
 
    private void Awake()
    {
        for (int i = 0; i < initialSize; i++)
        {
            Projectile projectile = Instantiate(projectilePrefab, transform);
            projectile.SetPool(this);
            projectile.gameObject.SetActive(false);
            inactive.Push(projectile);
        }
    }
 
    public Projectile Get()
    {
        Projectile projectile = inactive.Count > 0
            ? inactive.Pop()
            : Instantiate(projectilePrefab, transform);
 
        projectile.SetPool(this);
        projectile.gameObject.SetActive(true);
        return projectile;
    }
 
    public void Release(Projectile projectile)
    {
        projectile.gameObject.SetActive(false);
        inactive.Push(projectile);
    }
}