참고자료
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);
}
}
결과: