对象池 :用在量大,重复利用高的地方。
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IRecycleable
{
//回收关闭
void OnRecycle();
//重启
void OnReuse();
}
//泛型对象池
public class ObjectPool<T> where T : IRecycleable
{
int size;
//容器
Queue<T> container;
//放入对象池的GameObject 元素
GameObject moudle;
private static ObjectPool<T> _self;
public static ObjectPool<T> GameInstance
{
get
{
if (_self == null)
Debug.LogError ("This pool NOT Created yet");
return _self;
}
}
//设置对象池大小 和初始容量
public ObjectPool (int srcSize , GameObject _moudle)
{
container = new Queue<T> ();
size = srcSize;
moudle = _moudle;
for(int i = 0; i < srcSize; i++)
{
GameObject obj = GameObject.Instantiate (moudle) as GameObject;
T temp = obj.GetComponent<T> ();
if (temp == null)
{
Debug.LogError ("The GameObject Can't Recycle");
break;
}
temp.OnRecycle ();
container.Enqueue (temp);
}
}
//对象池元素
public T GetObjectFromPool()
{
if(container.Count == 0)
{
GameObject obj = GameObject.Instantiate (moudle) as GameObject;
T temp = obj.GetComponent<T> ();
container.Enqueue (temp);
}
T r = container.Dequeue ();
r.OnReuse ();
return r;
}
//回收和向对象池添加元素
public void Recycle(GameObject obj)
{
T temp = obj.GetComponent<T> ();
IRecycleable r = (IRecycleable)temp;
r.OnRecycle ();
container.Enqueue (temp);
}
}
对象池使用:
列代码:
//创建hudController对象池,资源为resources.load加载
GameObject obj = Resources.Load<GameObject>("HUD");
hudPool = new ObjectPool<HUDController> (5, obj);
//重对象池中获取一个特定类型的的对象
HUDController h = hudPool.GetObjectFromPool ();
//使用完后回收到对象池
hudPool.Recycle (h.gameObject);