using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
public class ObjectPool
{
public event Action<GameObject> OnSpawnedEvent;
public event Action<GameObject> onDespawnedEvent;
public GameObject Prefab;//注释这个池子里面的原始东西。这个物体时子弹的话 ,那么这个池子就只生成和销毁子弹了。
public int InstancesToPreallocate = 5;//池子里面最多能有个数
public int InstancesToAllocateIfEmpty = 1;//池子最少的个数
public int HardLimit = 5;//最多限制个数
public int InstancesToMaintainInPool = 5;
public bool PersistBetweenScenes = false;
private Stack<GameObject> _gameObjectPool;
public void Initialize()//初始化池子
{
_gameObjectPool = new Stack<GameObject>(InstancesToPreallocate);
AllocateGameObjects(InstancesToPreallocate);
}
public void ClearStack()//这里池子用的数据结构是栈 你也可以用链表,队列都行。这个方法是清空栈
{
if (_gameObjectPool.Count > InstancesToMaintainInPool)
{
for (int i = InstancesToMaintainInPool; i < _gameObjectPool.Count; i++)
{
Object.Destroy(_gameObjectPool.Pop());
}
}
}
public GameObject Spawn()//实例化一个游戏物体
{
var go = Pop();
return go;
}
public void RecycleObj(GameObject ob)//回收一个游戏物体,将物体设置成不可见,然后放到栈中
{
ob.transform.parent = Pools.Instance.gameObject.transform;
ob.SetActive(false);
_gameObjectPool.Push(ob);
}
private GameObject Pop()
{
if (_gameObjectPool.Count > 0)
{
return _gameObjectPool.Pop();
}
AllocateGameObjects(InstancesToAllocateIfEmpty);
return Pop();
}
public void ClearPool(bool shouldDestroyAllManagedObjects)//qing
{
while (_gameObjectPool.Count > 0)
{
var go = _gameObjectPool.Pop();
if (shouldDestroyAllManagedObjects)
Object.Destroy(go);
}
}
private void AllocateGameObjects(int count)
{
for (int n = 0; n < count; n++)
{
GameObject go = Object.Instantiate(Prefab.gameObject) as GameObject;
go.name = Prefab.name;
if (go.transform as RectTransform)
{
go.transform.SetParent(Pools.Instance.Transform, false);
go.SetActive(false);
}
else
{
go.transform.parent = Pools.Instance.Transform;
go.SetActive(false);
}
_gameObjectPool.Push(go);
}
}
}