public class Poolmanager();Monobehaviour
{
public GameObject obj; //缓冲池中的对象
public int Initcapacity; //初始容量
private List<int > _AvailableIDLIst; //可用的ID集合
private Dictionary<int , GameObject> _AllObject; //缓冲池
private int _StartID=0;
}
void Start()
{ //分配空间
_AvailableIDList=new List<int >(Initcapacity);
_AllObject=new Dictionary<int ,GameObject>(Initcapacity);
//初始化对象池
InitPool();
}
void InitPool()
{
int endID=_StartID+Initcapacity;
for(int i=_StartID;i<endID;i++)
{
GameObject newObj= Instantiate(Obj) as GamgObject;
newObj.SetActive(false);
_AvailableIDList.Add(i);
_AllObject.Add(i,newObj);
}
_StartId=endID; //下次初始化缓冲池时从 新的起点开始
}
public KeyValuePair<int , GameObject> PickObj() //取出一个键值对
{
//如果可用的Id没有了
if(_AvailableIDList.Count==0)
{
//重新初始化池子
InitPool();
}
int id =_AvailableIDList[0];
_AvailableIDList.Remove(id); //取出对象
_AllObject[id].SetActive(true); //显示出来
return new KeyValuePair<int ,GameOblect>(id,_AllObject[id]);
}
public void RecyleObj( int id)
{
_AllObject[id].SetAvtive(false);
_AvailableIDList.Add(id);
if( _AllObject[id].GetComponent<RigidBody>())
{
_AllObject[id].GetComponent<RigidBody>().velecity=zero;
}
}
//使用缓冲池取出
public class GameController : MonoBehaviour
{
public GameObject Cube; //克隆Cube原型
void Start ()
{
Cursor.visible = false;
Cube.AddComponent();
Cube.GetComponent().collisionDetectionMode = CollisionDetectionMode.Continuous;
for (int i = 0; i < 10; i++)
{
for (int J = 0; J < 10; J++)
{
GameObject temp = Instantiate(Cube) as GameObject;
temp.transform.position = temp.transform.position + new Vector3(J + 1, i, 0);
}
}
private Ray _ray;
public Texture tex;
private Vector3 _vecMoisePosition;
public Poormanager PM;
void Update ()
{
if (Input .GetMouseButtonDown (0))
{ _ray = Camera.main.ScreenPointToRay(Input.mousePosition);
KeyValuePairkvp = PM.PickObj();
kvp.Value.transform.position = Camera.main.transform.position;
kvp .Value .GetComponent(RigidBody).AddForce (_ray.direction * 100, ForceMode.Impulse);
kvp.Value.GetComponent(DestroyBullet).GetID(kvp.Key);
kvp .Value .GetComponent(RigidBody).collisionDetectionMode =CollisionDetectionMode.ContinuousDynamic;
}
}//end_Update
private void OnGUI()
{
_vecMoisePosition = Input.mousePosition;
GUI.DrawTexture(new Rect(_vecMoisePosition.x - 10, Screen.height - _vecMoisePosition.y - 10, 20, 20), tex);
}
//使用缓冲室回收
public class DestroyBullet : MonoBehaviour
{
public Poormanager PM;
private int BulletID;
// 当摄像机不可见的时候调用
///private void OnBecameInvisible()
{
PM.RecyleObj(BulletID);
}
public void GetID(int id )
{ BulletID = id; }}