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);
}
}
}