Files
plugin-library/Assets/Main/HotfixUpdateScript/Runtime/HotUpdate/Init/ClassObjectPool/IClassPool.cs
2025-07-02 10:05:26 +08:00

136 lines
3.8 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using YooAsset;
namespace Main
{
/// <summary>
/// 类对象池
/// </summary>
public interface IClassPool
{
/// <summary>
/// 将类对象存进池里
/// </summary>
/// <param name="obj"></param>
void Creation(GameObject obj);
/// <summary>
/// 从未激活池里面取类对象,并放入激活池
/// </summary>
/// <returns></returns>
GameObject Spawn(Transform parent);
/// <summary>
/// 从激活池中释放类对象到未激活池中
/// </summary>
GameObject RecycleSpawn(GameObject obj);
/// <summary>
/// 回收类对象
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
/// <summary>
/// 清空类对象池
/// </summary>
void RecycleAll();
int GetPolLength();
}
public class ClassObjectPool:IClassPool
{
private AssetHandle poolObject;
/// <summary>
/// 回收对象的父物体
/// </summary>
private Transform recycle;
protected List<GameObject> activepool = new List<GameObject>();
protected Stack<GameObject> inactivepool = new Stack<GameObject>();
//没有回收的个数
protected int noRecycleCount;
public ClassObjectPool(AssetHandle poolObject,Transform recycle)
{
this.poolObject = poolObject;
this.recycle = recycle;
}
/// <summary>
/// 将类对象存进池里
/// </summary>
/// <param name="obj"></param>
public void Creation(GameObject obj)
{
inactivepool.Push(obj);
noRecycleCount++;
}
/// <summary>
/// 从未激活池里面取类对象,并放入激活池
/// </summary>
/// <param name="createIfPoolEmpty">如果为空是否new出来</param>
public GameObject Spawn(Transform parent)
{
GameObject obj = null;
if(noRecycleCount>0)
{
obj = inactivepool.Pop();
obj.transform.SetParent(parent);
noRecycleCount--;
if(obj==null)
Debug.LogErrorFormat("对象池中不存在此对象【{0}】请排查代码", obj);
}
else
{
obj= poolObject.InstantiateSync(parent);
}
obj.transform.localPosition = Vector3.zero;
obj.transform.localRotation = Quaternion.identity;
obj.transform.localScale = Vector3.one;
obj.SetActive(true);
activepool.Add(obj);
return obj;
}
/// <summary>
/// 从激活池中释放类对象到未激活池中
/// </summary>
public GameObject RecycleSpawn(GameObject obj)
{
if(obj!=null&&activepool.Contains(obj))
{
activepool.Remove(obj);
inactivepool.Push(obj);
obj.transform.parent = recycle;
obj.gameObject.SetActive(false);
noRecycleCount++;
}
return null;
}
/// <summary>
/// 清空类对象池
/// </summary>
public void RecycleAll()
{
noRecycleCount=0;
foreach (var pool in inactivepool)
{
GameObject.Destroy(pool);
}
inactivepool.Clear();
foreach (var pool in activepool)
{
GameObject.Destroy(pool);
}
activepool.Clear();
}
public int GetPolLength()
{
return inactivepool.Count;
}
}
}