스파르타 게임개발종합반(Unity)/TIL - 본캠프 매일 공부 기록

2024.05.23 TIL - 오브젝트 풀링, UnityEngine.Pool, ObjectPool

테크러너 2024. 5. 23.

유니티에서 제공하는 오브젝트 풀링

이전에 오브젝트 풀링을 직접 작성해본적이 있다.▼

2024.05.14 - [Unity/스파르타 게임개발종합반 TIL] - 2024.05.14 TIL - Queue를 활용한 오브젝트 풀(ObjectPool)

 

그런데 유니티에서도 오브젝트 풀링 기능을 제공해주고 있다.

using UnityEngine.Pool;

유니티에서 제공하는 오브젝트 풀링을 사용하려면 위의 코드를 추가해줘야한다.

 

공식 문서▼

https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.html

 

이중에서 사용한 것은 `ObjectPool`이다.

오브젝트 풀링에는 다양한 방식이 있는데 그중에서 "최소 50개의 오브젝트 수 보장, 부족할 경우 누적 300개까지 추가 생성, 300개가 넘어갈 경우 임시로 생성 후 반환 시 파괴"하는 로직을 작성해볼 것이다.

 

ObjectPool<GameObject> pool = new ObjectPool<GameObject>(
    CreateObject,      // 객체 생성 메서드
    OnGetPool,         // 객체 풀에서 가져올 때 호출되는 메서드
    OnReleasePool,     // 객체 풀에 반환할 때 호출되는 메서드
    OnDestroyPool,     // 객체 파괴 시 호출되는 메서드
    collectionChecks,  // 컬렉션 체크 여부
    minSize,           // 초기 풀 크기
    maxSize            // 최대 풀 크기
);

위의 코드처럼 매개변수에 메서드명을 넣어서 초기화해주면 된다.

 

using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Pool;

public class ObjectPool : MonoBehaviour
{
    private ObjectPool<GameObject> pool;
    private const int minSize = 50;
    private const int maxSize = 300;

    void Awake()
    {
        pool = new ObjectPool<GameObject>(CreateObject, OnGetPool, OnReleasePool, OnDestroyPool, false, minSize, maxSize);
    }

    private GameObject CreateObject()
    {
        GameObject obj = new GameObject();
        obj.SetActive(false);
        return obj;
    }

    public GameObject GetObject()
    {
        return pool.Get();
    }

    public void ReleaseObject(GameObject obj)
    {
        pool.Release(obj);
    }

    private void OnGetPool(GameObject obj)
    {
        obj.SetActive(true);
    }

    private void OnReleasePool(GameObject obj)
    {
        obj.SetActive(false);
    }

    private void OnDestroyPool(GameObject obj)
    {
        Destroy(obj);
    }
}

객체 풀에서 가져올 때 Pool이 비어있다면 `CreateObject`를 호출하여 생성해준다.

풀 반환시 maxSize 넘어가면 자동으로 파괴가 된다.

반응형

댓글