类对象池存储的是类,当需要几十几百甚至更多的类进行频繁的使用和销毁时,就该使用类对象池了。
基本类对象池:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClassObjectPool<T> where T:class,new()
{
protected Stack<T> pool = new Stack<T>();
//最大对象个数 <=0表示不限制个数
protected int maxCount;
//没有别回收的个数
protected int noRecycleCount;
public ClassObjectPool(int maxCount)
{
this.maxCount = maxCount;
for (int i = 0; i < maxCount; i++)
{
pool.Push(new T());
}
}
/// <summary>
/// 从池里面取类对象
/// </summary>
/// <param name="createIfPoolEmpty">如果为空是否new出来</param>
public T Spawn(bool createIfPoolEmpty)
{
if(maxCount>0)
{
T rtn = pool.Pop();
if(rtn==null)
{
if(createIfPoolEmpty)
{
rtn = new T();
}
}
noRecycleCount++;
return rtn;
}
else
{
if(createIfPoolEmpty)
{
T rtn = new T();
noRecycleCount++;
return rtn;
}
}
return null;
}
/// <summary>
/// 回收类对象
/// </summary>
public bool Recycle(T obj)
{
if (obj == null)
return false;
noRecycleCount--;
if(pool.Count>=maxCount&&maxCount>0)
{
obj = null;
return false;
}
pool.Push(obj);
return true;
}
}
先来个单例基类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T:new()
{
private static T _instance;
public static T Instance
{
get
{
if(_instance==null)
{
_instance = new T();
}
return _instance;
}
}
}
然后新建一个类对象池的管理方法,用来获取或者创建类对象池。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ObjectManager : Singleton<ObjectManager>
{
#region 类对象池的使用
protected Dictionary<Type, object> classObjectPoolDic = new Dictionary<Type, object>();
/// <summary>
/// 创建类对象池,创建完成后在外面可以保存ClassObjectPool<T>,然后调用Spawn和Recycle来创建和回收类对象
/// </summary>
public ClassObjectPool<T> GetOrCreateClassObjectPool<T>(int maxCount)where T:class,new()
{
Type type = typeof(T);
object obj = null;
if(!classObjectPoolDic.TryGetValue(type,out obj) || obj==null)
{
ClassObjectPool<T> newPool = new ClassObjectPool<T>(maxCount);
classObjectPoolDic.Add(type, newPool);
return newPool;
}
return obj as ClassObjectPool<T>;
}
#endregion
}
用法:
/// <summary>
/// AssetBundleItem类对象池
/// </summary>
protected ClassObjectPool<AssetBundleItem> assetBundleItemPool = ObjectManager.Instance.GetOrCreateClassObjectPool<AssetBundleItem>(500);
这里创建了500个AssetBundleItem类,
取出的时候使用:
AssetBundleItem item = assetBundleItemPool.Spawn(true);
销毁的时候使用:
assetBundleItemPool.Recycle(item);