using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PoolManager : MonoBehaviour
{
public GameObject Obj; // 池子里面的对象
public int InitCapacity; // 初始容量
private List<int> _AvailableIDList; // 可用的ID集合
private Dictionary<int, GameObject> _AllObjDic; // 池子
private int _StartID = 0;
void Start ()
{
// 分配空间
_AvailableIDList = new List<int>(InitCapacity);
_AllObjDic = new Dictionary<int, GameObject>(InitCapacity);
// 初始化对象池
InitPool();
}//end_Start
/// <summary>
/// 初始化对象池
/// </summary>
void InitPool()
{
int endID = _StartID + InitCapacity;
for (int i = _StartID; i < endID; i++)
{
GameObject newObj = Instantiate(Obj) as GameObject;
newObj.SetActive(false);
_AvailableIDList.Add(i);
_AllObjDic.Add(i, newObj);
}
_StartID = endID;
}
/// <summary>
/// 取出一个键值对,e.g. 1001, Obj 代表ID是1001的物体被取到,1001可以在放回池子的时候用到
/// </summary>
/// <returns>取出的键值对</returns>
public KeyValuePair<int, GameObject> PickObj()
{
// 如果可用的ID没有了
if (_AvailableIDList.Count == 0)
{// 重新初始化池子
InitPool();
}
int id = _AvailableIDList[0];
_AvailableIDList.Remove(id);
// 池子里面对应ID的对象显示出来,代表从池子中取出了该对象
_AllObjDic[id].SetActive(true);
return new KeyValuePair<int, GameObject>(id, _AllObjDic[id]);
}
/// <summary>
/// 根据ID回收对象到对象池当中
/// </summary>
/// <param name="id">对象的ID</param>
public void RecyleObj(int id)
{
// 让池子中的炮弹隐藏起来表示重新放回了缓冲池
_AllObjDic[id].SetActive(false);
// 放回池子之后,可用的ID也要添加
_AvailableIDList.Add(id);
if (_AllObjDic[id].GetComponent<Rigidbody>())
{// 让炮弹的速度变为0
_AllObjDic[id].GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
}
网友评论