Unity Object Pooling

용준·2024년 3월 25일
0

Unity

목록 보기
15/20

참고자료
https://wergia.tistory.com/203
https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html


오브젝트 풀링(Object Pooling)은 반복적으로 생성되고 제거되는 오브젝트를 미리 생성해 두고 필요할 때마다 활성화 및 비활성화하여 재사용하는 방법입니다.

오브젝트를 반복적으로 생성하고 소멸시키는 과정에서 발생하는 오버헤드를 줄이고, 성능을 향상시키며 메모리 사용량을 최적화하는 데 도움이 됩니다.

유니티 21.x 버전부터 공식 API로 지원합니다.


장점

  • 성능 개선
    오브젝트를 반복해서 생성하고 제거하는 과정에서 발생하는 메모리 할당 및 해제 오버헤드를 줄여 성능을 향상시킵니다.
  • 메모리 최적화
    오브젝트를 미리 생성하여 메모리 사용량을 최적화하고, 런타임 중에 오브젝트를 재사용하여 메모리 누수를 방지합니다.

단점

  • 초기 설정
    오브젝트 풀을 구현하려면 초기에 모든 오브젝트를 미리 생성하고 관리해야 합니다.
  • 유연성 감소
    오브젝트 풀링을 사용하면 오브젝트의 동적 생성 및 제거가 어려워질 수 있습니다. 따라서 동적으로 오브젝트의 생성 및 제거가 필요한 경우에는 유연성이 감소할 수 있습니다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    public static ObjectPool instance;

    [SerializeField]
    private GameObject poolingObjectPrefab;

    Queue<Bullet> poolingObjectQueue = new Queue<Bullet>();

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }

        Initialize(10);
    }

    void Initialize(int initCount)
    {
        for (int i=0;i<initCount; i++)
        {
            poolingObjectQueue.Enqueue(CreateNewObject());
        }
    }

    Bullet CreateNewObject()
    {
        var newObj = Instantiate(poolingObjectPrefab).GetComponent<Bullet>();
        newObj.gameObject.SetActive(false);
        newObj.transform.SetParent(transform);
        return newObj;
    }

    public static Bullet GetObject()
    {
        if (instance.poolingObjectQueue.Count > 0)
        {
            var obj = instance.poolingObjectQueue.Dequeue();
            obj.transform.SetParent(null);
            obj.gameObject.SetActive(true);
            return obj;
        }
        else
        {
            var newObj = instance.CreateNewObject();
            newObj.gameObject.SetActive(true);
            newObj.transform.SetParent(null);
            return newObj;
        }
    }
    
    public static void ReturnObject(Bullet obj)
    {
        obj.gameObject.SetActive(false);
        obj.transform.SetParent(instance.transform);
        instance.poolingObjectQueue.Enqueue(obj);
    }
}

결과:

0개의 댓글

Powered by GraphCDN, the GraphQL CDN