본문 바로가기

TIL

23.11.15

Unity : 오브젝트 풀링

오브젝트 풀링은 오브젝트의 Pool, 즉 웅덩이를 만들어 놓고 그 안에서 필요할 때마다 오브젝트를 꺼내서 사용하는 것을 뜻합니다.

오브젝트를 생성하고 파괴하면 메모리의 할당과 해제가 되고, 이는 CPU가 할 일이 늘어나게 된다는 것입니다. 따라서 사용한 오브젝트를 파괴하지 않고 비활성화 해서 Pool안에 넣어놓고 필요하면 다시 사용하는 것이 오브젝트 풀링을 입니다. 

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

public class PoolManager : MonoBehaviour
{
    public static PoolManager Instance;
    List<GameObject>[] pools;
    Dictionary<string, int> objectIndex;

    private void Start()
    {
        if (Instance == null)
        {
            Instance = this;
        }

        if (Instance != this)
        {
            Destroy(gameObject);
        }

        pools = new List<GameObject>[10];
        objectIndex = new Dictionary<string, int>();
    }

    public void Set(string key)
    {
        if (!objectIndex.ContainsKey(key))
        {
            int index = objectIndex.Count;
            pools[index] = new List<GameObject>();
            objectIndex.Add(key, objectIndex.Count);
        }
    }

    public GameObject Get(string key)
    {
        GameObject select = null;

        if (objectIndex.TryGetValue(key, out int index))
        {
            foreach (GameObject item in pools[index])
            {
                if (!item.activeSelf)
                {
                    select = item;
                    select.SetActive(true);
                    break;
                }
            }
            if (!select)
            {
                select = Instantiate(gameObject, transform);
                pools[index].Add(select);
            }
        }

        return select;
    }
}

 

'TIL' 카테고리의 다른 글

23.11.17  (1) 2023.11.20
23.11.16  (0) 2023.11.17
23.11.14  (0) 2023.11.14
23.11.13  (0) 2023.11.13
23.11.10  (0) 2023.11.13