对象池一般应用于一些需要重复使用的物体,比如子弹、陨石,如果直接销毁会产生大量的碎片占用内存空间,最好的方式就是循环利用这些物体,可以创建一个空物体当做对象池,当要使用而没有时就会在对象池里创建一个新的对象,有就直接从对象池里调用,当不需要使用物体时就将物体放回对象池,这里涉及到了一个队列的应用,调用时出队,不用时入队;
public static ObjectPool instance;
static Queue<GameObject> Pool = new Queue<GameObject>();
public GameObject bullet;
GameObject obj;
public Transform parent;
void Start () {
instance = this;
}
private void Update()
{
Debug.Log("123456");
if (Input.GetButtonDown("Fire1"))
{
StartCoroutine(BulletLife());
}
}
IEnumerator BulletLife()
{
obj = Creat(bullet, Vector3.zero, Quaternion.identity);
obj.GetComponent<Rigidbody>().AddForce(obj.transform.forward * 100);
yield return new WaitForSeconds(2);
Delete(obj, parent.position, Quaternion.identity);
}
//创建游戏物体-----预制体,出生点,旋转,父物体
public GameObject Creat(GameObject _prefabs,Vector3 _pos,Quaternion qua)
{
GameObject g = null;
if (Pool.Count>0)
{
g = Pool.Dequeue();
g.SetActive(true);
g.transform.position = _pos;
}
else
{
g = Instantiate(_prefabs, _pos, qua);g.transform.SetParent(GameObject.FindGameObjectWithTag("Bullet").transform);
}
return g;
}
//游戏物体删除-----预制体,回到出生点位置,旋转
public static void Delete(GameObject _object,Vector3 _resoucesPos,Quaternion qua)
{
_object.SetActive(false);
_object.transform.position = _resoucesPos;
_object.transform.localRotation = qua;
Pool.Enqueue(_object);
}