缓存池模块优化

缓存池优化

之前的缓存池模块中存在的缺陷:

1、当调用已经在缓存池中的对象时,在unity层级中直接显现出来,不利于开发者的观察

2、 当游戏加载其他场景时,缓存池中仍然存储着之前已实例化对象的信息,占据着内存空间。

改进:

1、在缓存池中增加父节点用于分类不同的对象

2、定义新的函数,使得切换场景时重置缓存池

 

改进代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 抽屉中,池子中的一列容器
/// </summary>
public class PoolDate
{
   //抽屉中,对象挂载的父节点
   public GameObject fatherObj;
   //对象的容器
   public List<GameObject> poolList;
   public PoolDate(GameObject obj,GameObject poolObj)
  {
       //给我们的抽屉,创建一个父对象,并且把他作为我们Pool(衣柜)对象的子物体
       fatherObj = new GameObject(obj.name);
       fatherObj.transform.parent = poolObj.transform;
       poolList = new List<GameObject>() { };
       PushObj(obj);
  }
   /// <summary>
   /// 往抽屉里面压东西
   /// </summary>
   /// <param name="obj"></param>
   public void PushObj( GameObject obj)
  {
       //存起来
       poolList.Add(obj);
       //设置父对象
       obj.transform.parent = fatherObj.transform;
       //失活,让其隐藏
       obj.SetActive(false);
  }
   /// <summary>
   /// 从抽屉里面取东西
   /// </summary>
   /// <returns></returns>
   public GameObject GetObj()
  {
       GameObject obj = null;
       //取出第一个
       obj = poolList[0];
       poolList.RemoveAt(0);
       //激活,让其显示
       obj.SetActive(true);
       //断开父子关系
       obj.transform.parent = null;
       return obj;
  }
}

/// <summary>
/// 缓存池模块
/// </summary>
public class PoolMgr :BaseManager<PoolMgr>
{
   //缓存池容器(衣柜)
   public Dictionary<string, PoolDate> poolDic = new Dictionary<string, PoolDate>();

   private GameObject poolObj;
   /// <summary>
   /// 往抽屉拿东西
   /// </summary>
   /// <param name="name"></param>
   /// <returns></returns>
   public GameObject GetObj(string name)
  {
       GameObject obj = null;
       //有抽屉,并且抽屉里有东西
       if (poolDic.ContainsKey(name) && poolDic[name].poolList.Count > 0)
      {
           //从字典中取出,并移除
           obj = poolDic[name].GetObj();
      }
       else
      {
           obj = GameObject.Instantiate(Resources.Load<GameObject>(name));
           //把对象的名字改的和池子名字相同
           obj.name = name;
      }
       return obj;
  }
   /// <summary>
   /// 暂时不用的东西给抽屉
   /// </summary>
   public void PushObj(string name,GameObject obj)
  {
       if(poolObj == null)
      {
           poolObj = new GameObject("Pool");
      }
       
       //里面有抽屉
       if (poolDic.ContainsKey(name))
      {
           poolDic[name].PushObj(obj);
      }
       //里面没有抽屉
       else
      {
           poolDic.Add(name, new PoolDate (obj,poolObj));
      }
  }
   /// <summary>
   /// 清空缓存池的方法
   /// 只要用在场景切换时
   /// </summary>
   public void clear()
  {
       poolDic.Clear();
       poolObj = null;
  }
}

 

 

猜你喜欢

转载自www.cnblogs.com/wei1349/p/12811023.html
今日推荐