Unity

[Unity][개념,방법] 오브젝트 풀링(ObjectPool) 이란?

usingsystem 2022. 8. 25. 14:32
728x90

오브젝트 풀링

프로그래밍에서 오브젝트를 생성하거나 파괴하는 작업은 메모리가 많이드는 작업이다. 오브젝트 생성은 메모리를 새로 할당하고 리소스를 로드하는 등의 초기화하는 과정이 필요하며 오브젝트 파괴는 파괴 이후에 발생하는 가비지양이 상당하여 가비지 컬렉팅으로 인한 프레임 드랍이 발생할 수 있다.

 

이를 해결하기 위해서 사용되는 기법이 바로 오브젝트 풀링(Object pooling)이다.

 

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

 

Unity - Scripting API: ObjectPool<T0>

Object Pooling is a way to optimize your projects and lower the burden that is placed on the CPU when having to rapidly create and destroy new objects. It is a good practice and design pattern to keep in mind to help relieve the processing power of the CPU

docs.unity3d.com

 

구현

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


class Pool
{
    GameObject _prefab;
    IObjectPool<GameObject> _pool;

    public Pool(GameObject prefab)
    {
        _prefab = prefab;
        _pool = new ObjectPool<GameObject>(OnCreate, OnGet, OnRelease, OnDestroy, maxSize:1000);
    }

    public void Push(GameObject go)
    {
        _pool.Release(go);
    }
    public GameObject Pop()
    {
        return _pool.Get();
    }

    GameObject OnCreate()
    {
        GameObject go = GameObject.Instantiate(_prefab);
        go.name = _prefab.name;
        return go;
    }
     void OnGet(GameObject go)
    {
        go.SetActive(true);
    }
     void OnRelease(GameObject go)
    {
        go.SetActive(false);
    }
    void OnDestroy(GameObject go)
    {
        GameObject.Destroy(go);
    }
}
public class PoolManager
{
    Dictionary<string, Pool> _pools = new Dictionary<string, Pool>();

    public GameObject Pop(GameObject prefab)
    {
        if (_pools.ContainsKey(prefab.name) == false)
            CreatePool(prefab);

        return _pools[prefab.name].Pop();
    }

    public bool Push(GameObject go)
    {
        if (_pools.ContainsKey(go.name) == false)
            return false;

        _pools[go.name].Push(go);
        return true;
    }

    void CreatePool(GameObject prefab)
    {
        Pool pool = new Pool(prefab);
        _pools.Add(prefab.name, pool);
    }
}
728x90