Unity中对象池技术管理大量生成的对象

  • Post author:
  • Post category:其他


生活就像大海一样一望无际,却又充满希望

原理



  • 一个字典存储所有需要生成的对象队列,通过枚举值判断当前生成的对象类型




  • 当需要生成新对象的时候根据类型去从字典中对应列表中查找空闲对象并返回,




  • 如果对应列表中为空则需要实例化一个当前对象,




  • 在回收的时候将对象存到字典中对应的列表中去供下次生成时候使用。



    [Header("需要生成的对象")]
    public List<GameObject> DynamicLoadObject;
    [Tooltip("敌人Canvas父对象")]
    public Transform enemyHealthBarParent;
    /// <summary>
    /// 需要对象池生成的对象种类
    /// </summary>
    public enum ObjectType
    {
        Bullet,
        DeathEffect,
        AttackedEffect,
        EnemyBornEffect,
        Enemy,
        EnemyHealthBar,
        DamageValue,
        Grenade
    }
    //对象池存储当前生成对象
    Dictionary<ObjectType, List<GameObject>> keyValuePairs = new Dictionary<ObjectType, List<GameObject>>
    {
        {ObjectType.Bullet,new List<GameObject>() },
        {ObjectType.DeathEffect,new List<GameObject>() },
        {ObjectType.AttackedEffect,new List<GameObject>() },
        {ObjectType.EnemyBornEffect,new List<GameObject>() },
        {ObjectType.Enemy,new List<GameObject>() },
        {ObjectType.EnemyHealthBar,new List<GameObject>() },
        {ObjectType.DamageValue,new List<GameObject>() },
        {ObjectType.Grenade,new List<GameObject>() },
    };


    /// <summary>
    /// 根据传入的对象类型生成对应对象
    /// </summary>
    /// <param name="objectType">对象类型</param>
    /// <param name="position">对象位置</param>
    /// <param name="rotation">对象角度</param>
    /// <returns></returns>
    public GameObject SpawnObject(ObjectType objectType, Vector3 position, Quaternion rotation)
    {
        GameObject usableObject = null;
        //从当前池中找类型相同并空闲对象的返回
        if (keyValuePairs[objectType].Count > 0)
        {
            usableObject = keyValuePairs[objectType][0];
            keyValuePairs[objectType].RemoveAt(0);
            usableObject.SetActive(true);
            usableObject.transform.position = position;
            usableObject.transform.rotation = rotation;
            return usableObject;
        }
        //直接生成对象返回。
        if (objectType == ObjectType.EnemyHealthBar||objectType==ObjectType.DamageValue)
        {//如果生成的是血条UI,需要把生成的对象放置到Canvas下
            usableObject = Instantiate(DynamicLoadObject[(int)objectType], position, rotation, enemyHealthBarParent);
        }
        else
        {
            usableObject = Instantiate(DynamicLoadObject[(int)objectType], position, rotation, transform);
        }
        return usableObject;
    }
    /// <summary>
    /// 关闭当前对象并将对象添加到空闲对象池中
    /// </summary>
    /// <param name="objectType"></param>
    /// <param name="currentObj"></param>
    public void UnSpawn(ObjectType objectType, GameObject currentObj)
    {
        currentObj.SetActive(false);
        keyValuePairs[objectType].Add(currentObj);
    }

如果有任何问题欢迎大家批评指正。



版权声明:本文为a1191835397原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。