정의

자주 생성, 파괴되는 오브젝트를 미리 생성해 풀(Pool)에 보관하고 필요할 때 꺼내 쓰고 다시 반환해 재사용하는 패턴


용도

총알, 이펙트, 적 유닛 등 실행 중 생성 및 파괴 비용이 높은 오브젝트 관리


구현 방법

using System.Collections.Generic;
using UnityEngine;

public class ObjectPoolManager : MonoBehaviour
{
    [Header("Pool Setting")]
    public GameObject prefab;       // 풀링할 프리팹
    public int initialSize = 10;    // 초기 생성 개수
    public bool willGrow = false;   // 풀 고갈 시 자동 확장 여부

    Queue<GameObject> pool;         // 사용 가능한 오브젝트 큐

    void Awake()
    {
        pool = new Queue<GameObject>();

        for (int i = 0; i < initialSize; i++)
        {
            GameObject obj = Instantiate(prefab);
            obj.SetActive(false);
            obj.transform.SetParent(transform);
            pool.Enqueue(obj);
        }
    }

    /// <summary>
    /// 풀에서 오브젝트를 꺼내 활성화 후 반환
    /// </summary>
    public GameObject GetObject(Vector3 position, Quaternion rotation)
    {
        GameObject obj;

        if (pool.Count > 0)
        {
            obj = pool.Dequeue();
        }
        else if (willGrow)
        {
            // 풀이 비어있고 확장 허용 시 새로 생성
            obj = Instantiate(prefab);
            obj.transform.SetParent(transform);
        }
        else
        {
            return null;
        }

        obj.transform.position = position;
        obj.transform.rotation = rotation;
        obj.SetActive(true);

        return obj;
    }

    /// <summary>
    /// 사용한 오브젝트를 풀에 반환
    /// </summary>
    public void ReturnObject(GameObject obj)
    {
        obj.SetActive(false);
        pool.Enqueue(obj);
    }
}

주의사항