using System.Collections.Generic;
using UnityEngine;
namespace Main
{
///
/// 类对象池
///
public interface IClassPool
{
///
/// 将类对象存进池里
///
///
void Creation(GameObject obj);
///
/// 从未激活池里面取类对象,并放入激活池
///
///
GameObject Spawn(Transform parent);
///
/// 从激活池中释放类对象到未激活池中
///
GameObject RecycleSpawn(GameObject obj);
///
/// 回收类对象
///
///
///
///
/// 清空类对象池
///
void RecycleAll();
int GetPolLength();
}
public class GameObjectPool:IClassPool
{
private GameObject poolObject;
///
/// 回收对象的父物体
///
private Transform recycle;
protected List activepool = new List();
protected Stack inactivepool = new Stack();
//没有回收的个数
protected int noRecycleCount;
public GameObjectPool(GameObject poolObject,Transform recycle)
{
this.poolObject = poolObject;
this.recycle = recycle;
}
///
/// 将类对象存进池里
///
///
public void Creation(GameObject obj)
{
inactivepool.Push(obj);
noRecycleCount++;
}
///
/// 从未激活池里面取类对象,并放入激活池
///
/// 如果为空是否new出来
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;
}
///
/// 从激活池中释放类对象到未激活池中
///
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;
}
///
/// 清空类对象池
///
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;
}
}
}