using System.Threading;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
public GameObject objectToPool;
public List thePool = new List();
public int maxNum = 30;
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < maxNum; i++)
{
thePool.Add(Instantiate(objectToPool));
thePool[i].transform.parent=this.transform;
thePool[i].SetActive(false);
}
}
///
/// 如果要生成多个预制体,使用对象池可以增强性能
/// 使用对象池在游戏加载时就生成一定数量的预制体,在游戏中不需要在次生成,提高性能
///
///
///
///
public GameObject SpawnObject(Vector3 pos,Quaternion rot)
{
GameObject toReturn;
if (thePool.Count > 0)
{
toReturn = thePool[0];
thePool.RemoveAt(0);
}
else
{ // 防止对象池中设置的数量不够造成报错
toReturn = Instantiate(objectToPool);
toReturn.transform.parent = this.transform;
}
toReturn.SetActive(true);
toReturn.transform.position = pos; // 设置位置
toReturn.transform.rotation = rot; // 设置旋转
return toReturn;
}
///
/// 游戏物体需要销毁时,回到对象池中
///
///
public void objectBack(GameObject againToPool)
{
thePool.Add(againToPool);
againToPool.SetActive(false);
}
}