Source file unity-csharp/nature-of-code/particle-system-2d/ParticlePool2D.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: a simple object pool for reusable 2D particles
// Related pages: [[particle-systems-design]], [[overview-unity-nature-of-code-examples]]
 
using System.Collections.Generic;
using UnityEngine;
 
public class ParticlePool2D : MonoBehaviour
{
    [SerializeField] private Particle2D particlePrefab;
    [SerializeField] private int initialCapacity = 64;
 
    private readonly Stack<Particle2D> available = new Stack<Particle2D>();
 
    private void Awake()
    {
        for (int i = 0; i < initialCapacity; i++)
        {
            available.Push(CreateInstance());
        }
    }
 
    public Particle2D Get()
    {
        return available.Count > 0 ? available.Pop() : CreateInstance();
    }
 
    public void Release(Particle2D particle)
    {
        particle.Deactivate();
        particle.transform.SetParent(transform);
        available.Push(particle);
    }
 
    private Particle2D CreateInstance()
    {
        if (particlePrefab == null)
        {
            Debug.LogError("ParticlePool2D needs a Particle2D prefab.");
            return null;
        }
 
        Particle2D instance = Instantiate(particlePrefab, transform);
        instance.Deactivate();
        return instance;
    }
}