Unity自带对象池方法 (2021.1版本之后才有)
直接继承该类,然后根据需要重写OnCreatePoolItem、OnGetPoolItem、OnReleasePoolItem、OnDestroyPoolItem方法即可
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool; //需要引用该命名空间
public class BasePool<T> : MonoBehaviour where T :Component
{
ObjectPool<T> pool;
[SerializeField] protected T prefab; //物品预制件
[SerializeField] int defaultSize = 100; //默认分配栈的空间
[SerializeField] int maxSize = 500; //对象池的栈空间的最大上限
[Header("Count Pool")]
[SerializeField] int activeCount; //对象池中当前激活的对象的个数
[SerializeField] int inactiveCount; //对象池中未激活的对象的个数
[SerializeField] int totalCount; //对象池中总物体个数
public int ActiveCount => pool.CountActive;
public int InactiveCount => pool.CountInactive;
public int TotalCount => pool.CountAll;
//第一个参数时创建对象池委托
//第二个参数是获得对象委托
//第三个是释放对象委托
//第四个是销毁对象委托
//第五个是开启对象回收检测功能
//第六个是默认容量
//第七个是最大容量
protected void Initialize(bool collectionCheck = true)=>
pool = new ObjectPool<T>(OnCreatePoolItem, OnGetPoolItem, OnReleasePoolItem, OnDestroyPoolItem, true, defaultSize, maxSize);
//销毁对象方法
protected virtual void OnDestroyPoolItem(T obj)
{
Destroy(obj.gameObject);
}
//释放对象方法
protected virtual void OnReleasePoolItem(T obj)
{
obj.gameObject.SetActive(false);
}
//获取对象方法
protected virtual void OnGetPoolItem(T obj)
{
obj.gameObject.SetActive(true);
}
//创建对象方法
protected virtual T OnCreatePoolItem()=> Instantiate(prefab, transform);
//获取对象池中的对象
public T Get() => pool.Get();
//使用完毕后放回对象池中
public void Release(T obj) => pool.Release(obj);
//清除对象池
public void Clear() => pool.Clear();
}