본문 바로가기
UNITY/유니티게임스쿨

오브젝트 풀링

by 램플릿 2024. 9. 30.

ObjectPoolManager.cs

using UnityEngine;
using System.Collections.Generic;

public enum PooledObjectType
{
    Bullet,
    Enemy,
    Powerup
}

[System.Serializable]
public class PooledObject
{
    public PooledObjectType type;
    public GameObject prefab;
    public int poolSize;
}

public class ObjectPoolManager : MonoBehaviour
{
    public static ObjectPoolManager Instance;
    public List<PooledObject> objectsToPool;

    private Dictionary<PooledObjectType, Queue<GameObject>> poolDictionary;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else
        {
            Destroy(gameObject);
            return;
        }

        InitializePools();
    }

    private void InitializePools()
    {
        poolDictionary = new Dictionary<PooledObjectType, Queue<GameObject>>();

        foreach (PooledObject item in objectsToPool)
        {
            Queue<GameObject> objectPool = new Queue<GameObject>();

            for (int i = 0; i < item.poolSize; i++)
            {
                GameObject obj = Instantiate(item.prefab);
                obj.SetActive(false);
                objectPool.Enqueue(obj);
            }

            poolDictionary.Add(item.type, objectPool);
        }
    }

    public GameObject SpawnFromPool(PooledObjectType type, Vector3 position, Quaternion rotation)
    {
        if (!poolDictionary.ContainsKey(type))
        {
            Debug.LogWarning("Pool with type " + type + " doesn't exist.");
            return null;
        }

        GameObject objectToSpawn = poolDictionary[type].Dequeue();

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

        IPooledObject pooledObj = objectToSpawn.GetComponent<IPooledObject>();
        if (pooledObj != null)
        {
            pooledObj.OnObjectSpawn();
        }

        return objectToSpawn;
    }

    public void ReturnToPool(PooledObjectType type, GameObject objectToReturn)
    {
        if (!poolDictionary.ContainsKey(type))
        {
            Debug.LogWarning("Pool with type " + type + " doesn't exist.");
            return;
        }

        IPooledObject pooledObj = objectToReturn.GetComponent<IPooledObject>();
        if (pooledObj != null)
        {
            pooledObj.OnObjectReturn();
        }

        objectToReturn.SetActive(false);
        poolDictionary[type].Enqueue(objectToReturn);
    }
}

public interface IPooledObject
{
    void OnObjectSpawn();
    void OnObjectReturn();
}

// 사용 예시
public class Bullet : MonoBehaviour, IPooledObject
{
    public void OnObjectSpawn()
    {
        // 총알이 스폰될 때 초기화 로직
    }

    public void OnObjectReturn()
    {
        // 총알이 풀로 반환될 때 정리 로직
    }

    private void Update()
    {
        // 총알 이동 로직
        // 만약 총알이 수명이 다했거나 충돌했다면:
        // ObjectPoolManager.Instance.ReturnToPool(PooledObjectType.Bullet, gameObject);
    }
}

 

 

InputController.cs

using UnityEngine;

public class InputController : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            GameObject bullet = ObjectPoolManager.Instance.SpawnFromPool(PooledObjectType.Bullet, transform.position, Quaternion.identity);
            // 총알 발사 로직...
        }

        if (Input.GetKeyDown(KeyCode.E))
        {
            GameObject enemy = ObjectPoolManager.Instance.SpawnFromPool(PooledObjectType.Enemy, Random.insideUnitSphere * 10f, Quaternion.identity);
            // 적 생성 로직...
        }
    }
}

'UNITY > 유니티게임스쿨' 카테고리의 다른 글

csv Parser  (0) 2024.09.30
Unity 클라이언트와 서버 통신하기  (0) 2024.09.25
프로토버퍼  (0) 2024.09.23
쉐이더  (0) 2024.07.31
포스트 프로세싱  (0) 2024.07.30