对象池

最近在写游戏的时候用到了对象池。
对象池,算是设计模式吧。
对象池中包含若干提前准备好的若干实例,当需要时从对象池中提取,当不需要时,则重新放入对象池。
一方面,使用对象池不需要频繁的产生和销毁实例对象,另一方面,对象池中的实例如果不够程序调用才会继续产生实例,这大大节省了性能。
在这里插入图片描述
比如在这个游戏中用到了很多的平台,用对象池的话就会很明显的优化性能。
代码如下:

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);
    }
}

然后就可以在别的类中使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值