This commit is contained in:
2025-09-04 11:43:35 +08:00
parent 8872c20cf2
commit 60e4ef39ed
707 changed files with 1498 additions and 29309 deletions

View File

@@ -0,0 +1,135 @@
using System.Collections.Generic;
using UnityEngine;
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 GameObjectPool:IClassPool
{
private GameObject poolObject;
/// <summary>
/// 回收对象的父物体
/// </summary>
private Transform recycle;
protected List<GameObject> activepool = new List<GameObject>();
protected Stack<GameObject> inactivepool = new Stack<GameObject>();
//没有回收的个数
protected int noRecycleCount;
public GameObjectPool(GameObject 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= GameObject.Instantiate(poolObject,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;
}
}
}