什么是对象池?
为了方便对象的产生和回收,我们使用一个集合来存储不使用对象,当需要使用该对象时,从集合中取出来,不用时不进行销毁,而是将其取消激活,重新存入对象池中。
为什么要使用对象池?
当一个游戏需要频繁的创建和销毁对象时,为了不增加GC的性能消耗,可以考虑使用回收对象来达到复用的目的。(适用于频繁创建和销毁的对象)
对象池的实现
Pool(对象池):对存储对象的集合进行了适当的封装,用于单个游戏对象(预制体)的回收和复用。
代码:
public class Pool{
public string name = "";
public GameObject prefab;
Queue<GameObject> poolQueue = new Queue<GameObject>(); //使用队列存储对象池中的数据
//立即回收
public void Recycle(GameObject go)
{
go.GetComponent<IReset>().Reset();
go.SetActive(false);
poolQueue.Enqueue(go);
}
//延迟回收
public IEnumerator AutoRecycle(GameObject go, float delay)
{
//使用写成,延时回收
yield return new WaitForSeconds(delay);
Recycle(go);
}
//创建对象
public GameObject Create()
{
GameObject go = null;
if (poolQueue.Count > 0)
{
//对象池中有需要创建的对象,从对象池中取
go = poolQueue.Dequeue();
go.SetActive(true);
}
else
{
//当对象池中没有需要创建的对象时,创建对象
go = GameObject.Instantiate(prefab);
}
return go;
}
}
PoolMgr(对象池管理器):对对象池进行了进一步的封装,可以用于创建多个对象(预制体)的回收和服用,可以更加方便的使用对象池。(对象池模块化)。
代码:
public class PoolMgr : MonoBehaviour {
public Pool[] pools;
//对象池管理器使用单例
private static PoolMgr _instance;
public static PoolMgr Instance {
get {
return _instance;
}
}
void Awake() {
if (_instance == null)
{
_instance = this;
}
else
{
Destroy(this.gameObject);
}
}
//将对象池注册进字典
Dictionary<string, Pool> poolDir = new Dictionary<string, Pool>();
void Start () {
foreach (var item in pools)
{
poolDir.Add(item.name.ToLower(), item);
}
}
public GameObject CreateObj(string poolName)
{
Pool pool;
//TryGetValue获取与键相关联的值
if (poolDir.TryGetValue(poolName.ToLower(),out pool))
{
return pool.Create();
}
Debug.LogError(poolName + "不存在");
return null;
}
/// <summary>
/// 立即回收
/// </summary>
public void RecycleObjs(string poolName, GameObject go)
{
Pool pool;
if (poolDir.TryGetValue(poolName.ToLower(),out pool))
{
pool.Recycle(go);
}
}
/// <summary>
/// 延迟销毁
/// </summary>
/// <param name="poolName">对象池名字</param>
/// <param name="go">需要回收的对象</param>
/// <param name="delay">延迟时间</param>
public void RecycleObjs(string poolName, GameObject go, float delay)
{
StartCoroutine(DelayRecycle(poolName, go, delay));
}
IEnumerator DelayRecycle(string poolName, GameObject go, float delay)
{
//延迟调用的立即回收
yield return new WaitForSeconds(delay);
Pool pool;
if (poolDir.TryGetValue(poolName.ToLower(),out pool))
{
pool.Recycle(go);
}
}
}
注:对象池是一种用内存换运存的优化技术,只有大量频繁创建和销毁的对象使用对象池,才能起到优化作用,否则不具有优化效果。