프로그래밍
Unity Object Pool
tedhong
2023. 2. 9. 13:59
2013-11-15 글쓴이 TED HONG
[펌] Unity Object Pool
원본 주소 : http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_Lecture&no=280
1. 오브젝트를 일정 갯수 미리 생성해 pool 에서 꺼내쓰는 방법
2. 오브젝트 생성시 발생하는 딜레이를 줄일 수 있음
3. 재사용 가능
4. 메모리 사용량 예측 가능
using System.Collections;
using System.Collections.Generic;
/*
* Usage
*
* CGameObjectPool<GameObject> monster_pool;
* ...
*
* // Create monsters.
* this.monster_pool = new CGameObjectPool<GameObject>(5, () =>
{
GameObject obj = new GameObject("monster");
return obj;
});
...
// Get from pool
GameObject obj = this.monster_pool.pop();
...
// Return to pool
this.monster_pool.push(obj);
* */
public class CGameObjectPool<T> where T : class
{
// Instance count to create.
short count;
public delegate T Func();
Func create_fn;
// Instances.
Stack<T> objects;
// Construct
public CGameObjectPool(short count, Func fn)
{
this.count = count;
this.create_fn = fn;
this.objects = new Stack<T>(this.count);
allocate();
}
void allocate()
{
for (int i=0; i<this.count; ++i)
{
this.objects.Push(this.create_fn());
}
}
public T pop()
{
if (this.objects.Count <= 0)
{
allocate();
}
return this.objects.Pop();
}
public void push(T obj)
{
this.objects.Push(obj);
}
}