Pool Create

using UnityEngine;
using System.Collections.Generic;

public class ObjectPool : MonoBehaviour
{
    public GameObject prefabToPool;
    public int poolSize = 10;

    private List<GameObject> objectPool = new List<GameObject>();

    private void Start()
    {
        InitializeObjectPool();
    }

    private void InitializeObjectPool()
    {
        for (int i = 0; i < poolSize; i++)
        {
            GameObject obj = Instantiate(prefabToPool);
            obj.SetActive(false);
            objectPool.Add(obj);
        }
    }

    public GameObject GetPooledObject()
    {
        foreach (GameObject obj in objectPool)
        {
            if (!obj.activeInHierarchy)
            {
                obj.SetActive(true);
                return obj;
            }
        }

        // 오브젝트 풀에 사용 가능한 오브젝트가 없는 경우
        GameObject newObj = Instantiate(prefabToPool);
        newObj.SetActive(true);
        objectPool.Add(newObj);
        return newObj;
    }

    public void ReturnObjectToPool(GameObject obj)
    {
        obj.SetActive(false);
    }
}

 

 

Using Sample

public class YourScript : MonoBehaviour
{
    private ObjectPool objectPool;

    private void Start()
    {
        objectPool = GetComponent<ObjectPool>();
    }

    private void SpawnObjectFromPool()
    {
        GameObject newObj = objectPool.GetPooledObject();
        // 가져온 오브젝트를 사용 (위치 설정 등)
        newObj.transform.position = Vector3.zero;
    }

    private void ReturnObjectToPool(GameObject obj)
    {
        objectPool.ReturnObjectToPool(obj);
    }
}

'Development > C#' 카테고리의 다른 글

Lazy Loading Pattern  (0) 2023.12.27
Cashing  (0) 2023.12.27

+ Recent posts