using System;
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
namespace SK.Framework
{
public static class MonoObjectPool
{
///
/// 从对象池中获取实例
///
/// 对象类型
/// 对象实例
public static T Allocate() where T : MonoBehaviour, IPoolable
{
return MonoObjectPool.Instance.Allocate();
}
///
/// 回收对象
///
/// 对象类型
/// 回收对象实例
/// 回收成功返回true 否则返回false
public static bool Recycle(T t) where T : MonoBehaviour, IPoolable
{
return MonoObjectPool.Instance.Recycle(t);
}
///
/// 释放对象池
///
/// 对象类型
public static void Release() where T : MonoBehaviour, IPoolable
{
MonoObjectPool.Instance.Release();
}
///
/// 设置对象池缓存数量上限
///
/// 对象类型
/// 缓存数量上限
public static void SetMaxCacheCount(int maxCacheCount) where T : MonoBehaviour, IPoolable
{
MonoObjectPool.Instance.MaxCacheCount = maxCacheCount;
}
///
/// 设置对象创建方法
///
/// 对象类型
/// 创建方法
public static void CreateBy(Func createMethod) where T : MonoBehaviour, IPoolable
{
MonoObjectPool.Instance.CreateBy(createMethod);
}
}
public class MonoObjectPool : IObjectPool where T : MonoBehaviour, IPoolable
{
private static MonoObjectPool instance;
//对象池缓存数量上限 默认9
private int maxCacheCount = 9;
//对象池
private readonly Stack pool = new Stack();
//创建方法
private Func createMethod;
public static MonoObjectPool Instance
{
get
{
if (null == instance)
{
var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public);
var index = Array.FindIndex(ctors, m => m.GetParameters().Length == 0);
if (index == -1)
{
Debug.LogError($"{typeof(MonoObjectPool)} 类型不具有公有无参构造函数.");
}
else
{
instance = Activator.CreateInstance>();
}
}
return instance;
}
}
///
/// 当前池中缓存的数量
///
public int CurrentCacheCount
{
get
{
return pool.Count;
}
}
///
/// 缓存数量上限
///
public int MaxCacheCount
{
get
{
return maxCacheCount;
}
set
{
if (maxCacheCount != value)
{
maxCacheCount = value;
if (maxCacheCount > 0 && maxCacheCount < pool.Count)
{
int removeCount = pool.Count - maxCacheCount;
while (removeCount > 0)
{
T t = pool.Pop();
UnityEngine.Object.Destroy(t.gameObject);
removeCount--;
}
}
}
}
}
///
/// 获取实例
///
/// 对象实例
public T Allocate()
{
//若对象池中有缓存则从对象池中获取
T retT = pool.Count > 0
? pool.Pop()
: (createMethod != null ? createMethod.Invoke() : new GameObject().AddComponent());
retT.hideFlags = HideFlags.HideInHierarchy;
retT.IsRecycled = false;
return retT;
}
///
/// 回收对象
///
/// 回收对象实例
/// 回收成功返回true 否则返回false
public bool Recycle(T t)
{
if (null == t || t.IsRecycled) return false;
t.IsRecycled = true;
t.OnRecycled();
//若未达到缓存数量上限 放入池中
if (pool.Count < maxCacheCount)
{
pool.Push(t);
}
else
{
UnityEngine.Object.Destroy(t.gameObject);
}
return true;
}
///
/// 释放对象池
///
public void Release()
{
foreach (var o in pool)
{
UnityEngine.Object.Destroy(o.gameObject);
}
pool.Clear();
instance = null;
}
///
/// 设置创建方法
///
/// 创建方法
public void CreateBy(Func createMethod)
{
this.createMethod = createMethod;
}
}
}