using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 泛型类对象池
/// </summary>
/// <typeparam name="T"></typeparam>
public class ClassObjectPool<T> where T : class, new()
{
//对象池
protected Stack<T> m_Pool = new Stack<T>();
//最大对象个数,<=0表示不限个数
protected int m_MaxCount = 0;
//该对象池没有回收的对象个数
protected int m_NoRecycleCount = 0;
/// <summary>
/// 构造(传基础要创建的数量)
/// 在程序中New一个新类,会产生一定的GC,这个过程有一定的卡顿,频繁的New的话可能会频繁的卡顿
/// 在一帧内New出几百个对象肯定会非常卡顿,所以使用类对象池的技术,提前缓存我们要的类的基础对象,需要的时候到类对象池取出就行了
/// </summary>
/// <param name="maxcount"></param>
public ClassObjectPool(int maxcount)
{
m_MaxCount = maxcount;
for (int i = 0; i < maxcount; i++)
{
m_Pool.Push(new T());
}
}
/// <summary>
/// 从池里面取类对象
/// </summary>
/// <param name="creatIfPoolEmpty">如果为空是否new出来</param>
/// <returns></returns>
public T Spawn(bool creatIfPoolEmpty)
{
//如果对象池数量大于0
if (m_Pool.Count > 0)
{
//出栈一个
T rtn = m_Pool.Pop();
//如果栈顶元素为空
if (rtn == null)
{
//并且传过来的Bool值是允许栈内不够就创建
if (creatIfPoolEmpty)
{
//New一个
rtn = new T();
}
}
//该对象池没有回收的对象个数+1
m_NoRecycleCount++;
//返回对象
return rtn;
}
else//如果对象池数量小于0
{
//并且传过来的Bool值是允许栈内不够就创建
if (creatIfPoolEmpty)
{
//New一个
T rtn = new T();
//该对象池没有回收的对象个数+1
m_NoRecycleCount++;
//返回对象
return rtn;
}
}
return null;
}
/// <summary>
/// 回收类对象(把不用的对象再放回栈里,不是删除)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public bool Recycle(T obj)
{
//如果要回收的对象等于空
if (obj == null)
{
return false;
}
//该对象池没有回收的对象个数-1
m_NoRecycleCount--;
//如果对象池的最大个数超出了最大容量 并且 最大容量大于0
if (m_Pool.Count >= m_MaxCount && m_MaxCount > 0)
{
//直接让其等于空,等待GC回收(因为取的时候,对象池没有就会New一个,New的这个并不属于对象池)
obj = null;
//返回false,对象没有入栈
return false;
}
//入栈
m_Pool.Push(obj);
//返回true,对象入栈
return true;
}
}
单例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T : new()
{
private static T m_Instance;
public static T Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new T();
}
return m_Instance;
}
}
}
对象池管理类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ObjectManager : Singleton<ObjectManager>
{
#region 类对象池的使用
protected Dictionary<Type, object> m_ClassPoolDic = new Dictionary<Type, object>();
/// <summary>
/// 创建类对象池,创建完成以后外面可以保存ClassObjectPool<T>,然后调用Spawn和Recycle来创建和回收类对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="maxcount"></param>
/// <returns></returns>
public ClassObjectPool<T> GetOrCreatClassPool<T>(int maxcount) where T : class, new()
{
//获取类型
Type type = typeof(T);
object outObj = null;
//如果m_ClassPoolDic字典里,没有这个对象池
if (!m_ClassPoolDic.TryGetValue(type, out outObj) || outObj == null)
{
//就创建这个对象池,并且传数量创建基础对象
ClassObjectPool<T> newPool = new ClassObjectPool<T>(maxcount);
m_ClassPoolDic.Add(type, newPool);
return newPool;
}
return outObj as ClassObjectPool<T>;
}
#endregion
}