Unity通用框架搭建(四)—— 缓存池设计

前面一文基于Addressable的资源加载更新记录了资源的加载,本文将紧贴资源的加载,结合设计模式中的享元模式的理念设计对象缓存池,避免在游戏过程中频繁的进行创建和销毁的工作。

缓存池设计

基于Addressable的资源加载更新一文中有提到缓存池的结构,主要分为以下几大模块:

  • 缓存对象类:
    1、缓存对象类需要有当前正在使用的对象的缓存references使用列表,用来存储正在使用的对象
    2、使用caches,来存储在注销时候应该的销毁的对象,后期使用时直接复用,不在重新创建。
    3、清理参数Exceed,定时触发清理多余的缓存对象,保留部分,避免过多的缓存对象占用过多的内存。
    当程序需要加载某一对象,先判断是否存在缓存的对象,如果存在,直接将缓存对象出栈(caches采用堆栈结构存储),没有缓存对象才重新创建对象。当程序需要销毁对象时并不直接销毁,而是将对象放回至caches缓存池里,方便重复使用。
 private class CacheList
    {
        /// <summary>
        /// 资源地址
        /// </summary>
        public string Address;

        /// <summary>
        /// 缓存列表
        /// </summary>
        private Stack<T> caches = new Stack<T>();

        /// <summary>
        /// 正在使用的列表
        /// </summary>
        private HashSet<T> references = new HashSet<T>();

        /// <summary>
        /// 清理参数
        /// </summary>
        public float Exceed = AssetPoolManager.Exceed;

        /// <summary>
        /// 模板
        /// </summary>
        public UnityEngine.Object Prefab;

        private int maxReferenceNumber = 0;

        public bool isAddressableAssets;

        /// <summary>
        /// 总计缓存数量
        /// </summary>
        public int Count
        {
            get
            {
                return this.references.Count + this.caches.Count;
            }
        }


        /// <summary>
        /// 可以使用的缓存对象的数量
        /// </summary>
        public int CachesCount
        {
            get
            {
                return this.caches.Count;
            }
        }

        /// <summary>
        /// 添加使用项
        /// </summary>
        /// <param name="t"></param>
        public void AddReference(T t)
        {
            if (this.references.Add(t))
            {
                this.maxReferenceNumber = this.references.Count > this.maxReferenceNumber ? this.references.Count : this.maxReferenceNumber;
            }
        }

        /// <summary>
        /// 从缓存池中取出一个项使用
        /// </summary>
        /// <returns></returns>
        public T Pop()
        {
            if (this.caches.Count > 0)
            {
                T _reference = this.caches.Pop();
                this.AddReference(_reference);
                return _reference;
            }
            else
            {
                throw new System.Exception(string.Format("{0} CacheList's caches is empty but use pop", Prefab.name));
            }
        }

        /// <summary>
        /// 使用完成之后放回缓存池
        /// </summary>
        /// <param name="t"></param>
        public void Push(T t)
        {
            this.caches.Push(t);
            this.references.Remove(t);
            InitInfomation();
        }

        public void Delete(T t)
        {
            this.references.Remove(t);
            GameObject.Destroy(t.gameObject);
        }

        /// <summary>
        /// 使用计算
        /// </summary>
        internal void InitInfomation()
        {
            this.maxReferenceNumber = this.references.Count;
        }

        public void ClearCaches(Dictionary<T, CacheList> lookup)
        {
            foreach (var obj in this.caches)
            {
                lookup.Remove(obj);
                GameObject.Destroy(obj.gameObject);
            }
            foreach (var obj in this.references)
            {
                lookup.Remove(obj);
                GameObject.Destroy(obj.gameObject);
            }
            this.caches.Clear();
            this.references.Clear();
            Prefab = null;
            if (isAddressableAssets)
                AddressableManager.Instance.UnLoadAsset(Address);
        }

        /// <summary>
        /// 清理多余的缓存资源
        /// </summary>
        /// <returns></returns>
        public List<T> CleanCache()
        {
            int cleanCount = this.Count - ((int)(this.maxReferenceNumber * Exceed));
            if (cleanCount > 0)
            {
                List<T> list = new List<T>();
                for (int i = 0; i < cleanCount; i++)
                {
                    list.Add(this.caches.Pop());
                }
                return list;
            }
            return null;
        }
    }

缓存池实现逻辑AddressablePool

为方便不同的资源类型复用缓存池的逻辑,这里将采用泛型来实现缓存的逻辑,将CacheList类设计为AddressablePool的嵌入类类型。AddressablePool负责判断加载逻辑是使用缓存池的对象还是重新创建新的对象。

  • Dictionary<string, CacheList> pools :资源缓存池,用来缓存不用名字的资源
  • Dictionary<T, CacheList> lookup:为方便快速的定位缓存池对象,需要在创建对象的时候加入缓存查找表,以后后期的快速定位。
  • 添加模板:
    为实现通用性,游戏开发中可能存在不需要从本来加载模板的情况,界面本身已经存在GameObject了,这是不在需要加载的过程因此将添加模板的方法独立出来
public void AddTemplate(string address, UnityEngine.Object obj, bool isAddressabel=true, float Exceed = AddressableManager.Exceed)
    {
        if (!this.pools.ContainsKey(address))
        {
            CacheList cache = new CacheList();
            cache.Address = address;
            cache.Prefab = obj;
            cache.Exceed = Exceed;
            cache.isAddressableAssets = isAddressabel;
            isLoad = false;
            this.pools.Add(address, cache);
        }
        else
        {
            Helper.LogError("速查,出现同名资源:" + address);
        }
    }

在界面上直接传入模板(GameObject),也能使用这个缓存池的方法(在飘提示文字的时候经常用到),如果是需要加载,则在加载完成之后也调用该方法,只需要用个标记来区分是加载的模板还是外部直接传入的模板(资源清理时,加载的模板需要调用释放接口。界面上直接传入的则不用)。

  • 使用Addressable的异步加载,如果已经启动了加载程序则缓存加载完成回调,避免重复加载导致系统抛出异常。(Addressable的底层是基于AssetBundle设计的,重复加载会抛异常
 public void LoadAsset(string address, System.Action<T> onComplete, float Exceed = AssetPoolManager.Exceed)
    {
        isLoad = true;
        CacheList cache;
        if (this.pools.TryGetValue(address, out cache))
        {
            isLoad = false;
            var obj = LoadAssetByTemplate(address);
            if (obj != null)
            {
                onComplete(obj);
            }
            else
            {
                Helper.LogWarning("加载资源失败,请检查 :" + address);
            }
        }
        else
        {
            List<System.Action<T>> callBackList;
            if (loadCallBack.TryGetValue(address, out callBackList))
            {
                callBackList.Add(onComplete);
            }
            else
            {
                callBackList = new List<System.Action<T>>();
                callBackList.Add(onComplete);
                loadCallBack.Add(address, callBackList);
                AddressableManager.Instance.LoadAsset<GameObject>(address, (objAsset) => {
                    AddTemplate(address, objAsset, true, Exceed);
                    isLoad = false;
                    var list = loadCallBack[address];
                    if (objAsset != null)
                    {
                        if(list!=null&&list.Count>0)
                        {
                            for (int i = 0; i < list.Count; i++)
                            {
                                var obj = LoadAssetByTemplate(address);
                                list[i](obj);
                            }
                        }
                    }
                    else
                    {
                        Helper.LogWarning("加载资源失败,请检查 :" + address);
                    }
                    loadCallBack.Remove(address);
                }, () => {
                    Helper.LogWarning("加载资源失败,请检查 :" + address);
                });
            }
        }
    }
  • 多余缓存清理,缓存中设计了清理参数,定时器会定时触发清理函数。我们需要定时的将多余的缓存清理掉,比如(10个缓存保留3个即可)这个需要通过Exceed清理参数来控制
 private void cleanCache()
    {
        if (isLoad)
            return;
        InitInfomation();
        foreach (var info in this.pools)
        {
            List<T> temps = info.Value.CleanCache();
            if (temps != null)
            {
                foreach (var obj in temps)
                {
                    this.lookup.Remove(obj);
                    GameObject.Destroy(obj.gameObject);
                }
            }
        }
        List<string> deleteList = new List<string>();
        foreach (var info in this.pools)
        {
            if (info.Value.Count == 0)
            {
                info.Value.ClearCaches(this.lookup);
                deleteList.Add(info.Key);
            }
        }
        foreach (var info in deleteList)
        {
            pools.Remove(info);
        }
    }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值