QFramework学习笔记——资源加载《一》

资源加载的逻辑: 有缓存
在这里插入图片描述

资源加载的逻辑: 没有缓存00
在这里插入图片描述

资源加载器

using System;
using System.Collections;
using System.Collections.Generic;
using Object = UnityEngine.Object;

namespace QFramework
{
	public class ResLoader
	{	
		public T LoadSync<T>(string assetName) where T : Object
		{
			var res = GetOrCreateRes(assetName);

			if (res != null)
			{
				return res.Asset as T;
			}
			
			// 真正加载资源
			res = CreateRes(assetName);

			res.LoadSync();
			
			return res.Asset as T;
		}

		public void LoadAsync<T>(string assetName, Action<T> onLoaded) where T : Object
		{
			// 查询当前的 资源记录
			var res = GetOrCreateRes(assetName);

			if (res != null)
			{
				onLoaded(res.Asset as T);
				
				return;
			}

			// 真正加载资源
			res = CreateRes(assetName);

			res.LoadAsync(loadedRes =>
			{
				onLoaded(loadedRes.Asset as T);
			});
		}


		public void ReleaseAll()
		{
			mResRecord.ForEach(loadedAsset => loadedAsset.Release());

			mResRecord.Clear();
		}
		
		
		#region private	
		private List<Res> mResRecord = new List<Res>();

		private Res GetOrCreateRes(string assetName)
		{
			// 查询当前的 资源记录
			var res = GetResFromRecord(assetName);

			if (res != null)
			{
				return res;
			}

			// 查询全局资源池
			res = GetFromResMgr(assetName);

			if (res != null)
			{
				AddRes2Record(res);

				return res;
			}

			return res;
		}
		
		private Res CreateRes(string assetName)
		{
			Res res = null;

			if (assetName.StartsWith("resources://"))
			{
				res = new ResourcesRes(assetName);
			}
			else
			{
				res = new AssetBundleRes(assetName);
			}			
			
			ResMgr.Instance.SharedLoadedReses.Add(res);
			
			AddRes2Record(res);

			return res;
		}

		private Res GetResFromRecord(string assetName)
		{
			return mResRecord.Find(loadedAsset => loadedAsset.Name == assetName);
		}

		private Res GetFromResMgr(string assetName)
		{
			return ResMgr.Instance.SharedLoadedReses.Find(loadedAsset => loadedAsset.Name == assetName);
		}

		private void AddRes2Record(Res resFromResMgr)
		{
			mResRecord.Add(resFromResMgr);
				
			resFromResMgr.Retain();
		}
		
		#endregion
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值