最近在写游戏的时候用到了对象池。
对象池,算是设计模式吧。
对象池中包含若干提前准备好的若干实例,当需要时从对象池中提取,当不需要时,则重新放入对象池。
一方面,使用对象池不需要频繁的产生和销毁实例对象,另一方面,对象池中的实例如果不够程序调用才会继续产生实例,这大大节省了性能。
比如在这个游戏中用到了很多的平台,用对象池的话就会很明显的优化性能。
代码如下:
public class ObjectPool : MonoBehaviour
{
public static ObjectPool Instance;
private int InitSpawnCount = 5;
private ManagerVars vars;
private List<GameObject> normalPlantformList = new List<GameObject>();
private List<GameObject> commonPlantformList = new List<GameObject>();
private void Awake()
{
Instance = this;
vars = ManagerVars.GetManagerVars();
Init();
}
private void Init()
{
for(int i = 0; i < InitSpawnCount; i++)
{
InstantiateObject(vars.normalPlantform, ref normalPlantformList);
}
for (int i = 0; i < InitSpawnCount; i++)
{
for (int j = 0;j< vars.PlantformCommonGroup.Count; j++)
{
InstantiateObject(vars.PlantformCommonGroup[j], ref commonPlantformList);
}
}
for (int i = 0; i < InitSpawnCount; i++)
{
for (int j = 0; j < vars.PlantformWinterGroup.Count; j++)
{
InstantiateObject(vars.PlantformWinterGroup[j], ref winterPlantformList);
}
}
}
private GameObject InstantiateObject(GameObject prefeb,ref List<GameObject> list)
{
GameObject go = Instantiate(prefeb ,transform);
go.SetActive(false);
list.Add(go);
return go;
}
public GameObject GetNormalPlantform()
{
for(int i = 0; i < normalPlantformList.Count; i++)
{
if(normalPlantformList[i].activeInHierarchy == false)
{
return normalPlantformList[i];
}
}
return InstantiateObject(vars.normalPlantform, ref normalPlantformList);
}
/// <summary>
/// 获取普通平台
/// </summary>
/// <returns></returns>
public GameObject GetCommonPlantform()
{
for (int i = 0; i <commonPlantformList.Count; i++)
{
if (commonPlantformList[i].activeInHierarchy == false)
{
return commonPlantformList[i];
}
}
int ran = Random.Range(0, vars.PlantformCommonGroup.Count);
return InstantiateObject(vars.PlantformCommonGroup[ran] , ref commonPlantformList);
}
}
然后就可以在别的类中使用了。
来源:CSDN
作者:qq_43919462
链接:https://blog.csdn.net/qq_43919462/article/details/103672158