unity内存优化之AB包篇(微信小游戏)

1.搭建资源服务器使用(HFS软件(https://www.pianshen.com/article/54621708008/))

using System.Collections;
using System.Collections.Generic;
using UnityEngine;using System;public class Singleton<T> where T : class, new()
{private static readonly Lazy<T> lazy = new Lazy<T>(() => new T());public static T Instance { get { return lazy.Value; } }protected Singleton() { }
}public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{private static T _instance;public static T Instance{get{return _instance;}}protected virtual void Awake(){_instance = this as T;}
}

2.核心代码

using Cysharp.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.U2D;/*
内存优化之AB包篇(微信小游戏)
问题:如何优化AB包占用的内存,游戏的AB包资源卸载策略是什么
答:卸载时机
1.该AB包被引用次数为0时候,此时缓存一定的时间,当缓存时间为0时,就可以调用bundle.Unload(true);
缓存时间内被调用重置缓存时间,引用次数增加。
这部分主要用来处理偶尔打开的界面
2.首先维护一个已经加载的AB包资源大小总值,然后设置一个内存基准值,当总值大于内存基准值的时候,
此时去卸载那些引用次数为0的ab资源(优先卸载加载早的ab包资源)。
这部分用来处理短时间内,玩家打开过多大型界面场景,如果不这么处理,手机内存会占用高且发热会严重。引用次数的维护时机(引用次数始终不小于0)
1.例如一张图片 更换属于不同ab包的资源图片时,需要先将旧的ab包  引用次数减一,界面销毁时,最后动态加载的ab图片资源也需要减一,其他资源同理
2.同时加载一个AB资源时,在AB资源未加载完毕前,需要维护一个加载中的AB包资源实际被加载次数,
由于部分界面 正在动态加载的ab包资源未加载完毕时,此界面就可能已经被销毁,如果被销毁就需要将加载中的ab包的实际被加载次数减一。
3.当ab包资源加载完毕时,如果发现加载中的此ab包维护的实际被加载次数大于0,此时ab包的引用次数加一,同时实际被加载次数减一。
4.当界面销毁时,此界面的ab包和相关依赖的引用次数需要减一,动态加载的ab包资源也需要将引用次数减一5.!!!需要注意的是 当A依赖于B时,  A的最后一个实例被销毁时  A的引用变为0  但是B的引用此刻不变,除非A被卸载 才能将B的引用减一//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1//A被加载第二次 A引用为2 B引用为2//A被加载第3次 A引用为3 B引用为3// A被删除1次  引用为2  B引用为2//A被删除第二次 A引用为1 B引用为1//A被删除第3次 A引用为0 B引用为1//A被卸载时  B引用为0//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1//A被加载第二次 A引用为2 B引用为2// A被删除1次  引用为1  B引用为1//A被删除第二次 A引用为0 B引用为1//A被卸载时  B引用为0//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1// A被删除1次  A引用为0  B引用为1//A被卸载时  B引用为0*/
[SelectionBase]
public class LoadingAssetBundle
{private string abName;public string GetABName(){return abName;}private int realLoadedTimesInLoading = 0;//在加载中 被加载的真实次数(也就是剔除那些只加载不使用的部分,例如界面动态加载图片还没加载完毕 这个界面就被销毁了)public int GetRealLoadedTimesInLoading(){return realLoadedTimesInLoading;}public void AddRealLoadedTimesInLoading(){realLoadedTimesInLoading++;}public void ReduceRealLoadedTimesInLoading(){realLoadedTimesInLoading--;}public LoadingAssetBundle(string _abName){abName = _abName;AddRealLoadedTimesInLoading();}
}[SelectionBase]
public class LoadedAssetBundle
{private string abName;private AssetBundle bundle;private float cacheTimeBySenconds = 10;//缓存秒数不同ab可配置public float curLastCacheTime = 10;//当前剩余缓存时间public int referenceTimes = 0;//引用次数public long memoryValue = 0;//ab包大小public int loadIndexOrder = 0;//引用顺序 越小代表越早被引用private bool isUnload = false;//是否被卸载public LoadedAssetBundle(string _abName, AssetBundle _bundle, long _memoryValue, int _loadIndexOrder){isUnload = false;abName = _abName;bundle = _bundle;memoryValue = _memoryValue;//long size = long.Parse(unityWebRequest.GetResponseHeader("Content-Length"));ABManager.Instance.AddMemoryValue(_memoryValue);loadIndexOrder = _loadIndexOrder;}public AssetBundle GetAssetBundle(){return bundle;}public void AddRefer()//添加引用1{referenceTimes = referenceTimes + 1;curLastCacheTime = cacheTimeBySenconds;//重置剩余缓存1时间时间}public int ReduceRefer()//减少引用{if (referenceTimes > 0) {referenceTimes--;};return referenceTimes;}public void RefreshCacheLastTime(float time){if (referenceTimes == 0){ curLastCacheTime -= time;CheckCacheTimeUnload();}}private void CheckCacheTimeUnload(){if (isUnload) return;if (curLastCacheTime <= 0&& referenceTimes == 0) { bundle.Unload(true); //卸载时机1isUnload = true; ABManager.Instance.ReduceMemoryValue(memoryValue);ABManager.Instance.RemoveABRequest(abName);ABManager.Instance.ReduceDependciedRefer(abName);Debug.Log($"curLastCacheTime Unload{abName},Count={ABManager.Instance.cachedLoadedDic.Count}");}}public void CheckOverMemoryUnload(int curMinReferIndexOrder){if (isUnload) return;if (referenceTimes == 0 && ABManager.Instance.CheckOverMemoryMemoryReferenceValue())//&& curMinReferIndexOrder == loadIndexOrder{bundle.Unload(true);//卸载时机2isUnload = true;ABManager.Instance.ReduceMemoryValue(memoryValue);ABManager.Instance.RemoveABRequest(abName);ABManager.Instance.ReduceDependciedRefer(abName);Debug.Log($"Unload{abName}");}}public string GetABName(){return abName;}public bool IsUnLoad(){return isUnload;}
}public class ABManager : MonoSingleton<ABManager>
{public Dictionary<string, LoadedAssetBundle> cachedLoadedDic = new Dictionary<string, LoadedAssetBundle>();private Dictionary<string, LoadingAssetBundle> cachedLoadingDic = new Dictionary<string, LoadingAssetBundle>();private long memoryReferenceValue= 995406;//内存基准值private long curMemoryValue = 0;//内存当前值private int curReferIndexOrder = 0;//当前索引private int curMinReferIndexOrder = 0;//当前被加载最早的索引public void AddMemoryValue(long _memoryValue){curMemoryValue = curMemoryValue + _memoryValue;//print("curMemoryValue" + curMemoryValue);}public void ReduceMemoryValue(long _memoryValue){//Debug.Log("memoryValue" + _memoryValue);curMemoryValue = curMemoryValue - _memoryValue;curMinReferIndexOrder++;if (curMinReferIndexOrder  > curReferIndexOrder){curMinReferIndexOrder = curReferIndexOrder;}}public bool CheckOverMemoryMemoryReferenceValue(){return curMemoryValue > memoryReferenceValue;}private float checkSpan =  0.3f;public float time;List<string> removeList = new List<string>();public int CachedLoadedCount;private void CheckUnLoadCachedLoaded(){time += Time.fixedDeltaTime;if (time > checkSpan){time = 0;removeList.Clear();foreach (var item in cachedLoadedDic){if (!cachedLoadingDic.ContainsKey(item.Key)){item.Value.RefreshCacheLastTime(checkSpan);item.Value.CheckOverMemoryUnload(curMinReferIndexOrder);if (item.Value.IsUnLoad()) removeList.Add(item.Key);}}for (int i = 0; i < removeList.Count; i++){print($"removeList={removeList[i]}");cachedLoadedDic.Remove(removeList[i]);}}CachedLoadedCount = cachedLoadedDic.Count;}// Update is called once per framevoid FixedUpdate(){CheckUnLoadCachedLoaded();}private AssetBundle mainAB = null; //主包private AssetBundleManifest mainManifest = null; //主包中配置文件---用以获取依赖包private string basePath = "http://192.168.31.208/AssetBundles/";private string mainABName = "AssetBundles";public Dictionary<string, string> AssetNameToABName = new Dictionary<string, string>();public async UniTask<GameObject> LoadAsset(string assetName){string abName = assetName.ToLower() + ".ab";AssetBundle ab = await LoadABPackage(abName);//await UniTask.SwitchToMainThread();return ab.LoadAsset<GameObject>(assetName);}/// <summary>/// 加载图集里面的图片/// 案例///   Image a = nul;;///   if (a != null)///        ABManager.Instance.UnloadAsset(a);///    a = ABManager.Instance.LoadAtlasSprite(a);/// </summary>/// <param name="assetName"></param>/// <param name="textureName"></param>/// <returns></returns>public async UniTask<Sprite> LoadAtlasSprite(string assetName, string textureName){string abName = assetName.ToLower() + ".ab";AssetBundle ab = await LoadABPackage(abName);SpriteAtlas spriteAtlas = ab.LoadAsset<SpriteAtlas>(assetName);return spriteAtlas.GetSprite(textureName);}//单个包卸载public void ReduceRefer(string assetName){string abName = assetName.ToLower() + ".ab";if (cachedLoadingDic.ContainsKey(abName)){cachedLoadingDic[abName].ReduceRealLoadedTimesInLoading();}else{//--引用if (cachedLoadedDic.ContainsKey(abName)){int referValue =  cachedLoadedDic[abName].ReduceRefer();//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1//A被加载第二次 A引用为2 B引用为2//A被加载第3次 A引用为3 B引用为3// A被删除1次  引用为2  B引用为2//A被删除第二次 A引用为1 B引用为1//A被删除第3次 A引用为0 B引用为1//A被卸载时  B引用为0//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1//A被加载第二次 A引用为2 B引用为2// A被删除1次  引用为1  B引用为1//A被删除第二次 A引用为0 B引用为1//A被卸载时  B引用为0//  A依赖于B//  A被加载 会先加载B//那么A引用为1 B引用为1// A被删除1次  A引用为0  B引用为1//A被卸载时  B引用为0if (referValue > 0){ReduceDependciedRefer(abName);}}}}public void ReduceDependciedRefer(string abName){string[] dependencies = mainManifest.GetAllDependencies(abName);for (int i = 0; i < dependencies.Length; i++){if (cachedLoadedDic.ContainsKey(dependencies[i])){cachedLoadedDic[dependencies[i]].ReduceRefer();}}}//加载AB包private async UniTask<AssetBundle> LoadABPackage(string abName){//加载ab包,需一并加载其依赖包。if (mainAB == null){//获取ab包内容mainAB = await DownloadABPackage(mainABName);//获取主包下的AssetBundleManifest资源文件(存有依赖信息)mainManifest = mainAB.LoadAsset<AssetBundleManifest>("AssetBundleManifest");}//根据manifest获取所有依赖包的名称 固定API 保证不丢失依赖string[] dependencies = mainManifest.GetAllDependencies(abName);if (dependencies.Length > 0){var tasks = new List<UniTask>(); // 创建一个任务列表来存储异步操作//循环加载所有依赖包for (int i = 0; i < dependencies.Length; i++){//如果不在缓存则加入if (!cachedLoadedDic.ContainsKey(dependencies[i])) tasks.Add(LoadABPackage(dependencies[i]));else{cachedLoadedDic[dependencies[i]].AddRefer(); //++引用}}// 使用UniTask.WhenAll等待所有任务完成await UniTask.WhenAll(tasks);}//加载目标包 -- 同理注意缓存问题if (cachedLoadedDic.ContainsKey(abName)){cachedLoadedDic[abName].AddRefer(); //++引用Debug.Log($"ContainsKey{abName}");return (cachedLoadedDic[abName].GetAssetBundle());}else{await DownloadABPackage(abName);Debug.Log($"DownloadABPackage{abName}");return (cachedLoadedDic[abName].GetAssetBundle());}}//存儲下載操作Dictionary<string, UnityWebRequestAsyncOperation> ABRequestOpera = new Dictionary<string, UnityWebRequestAsyncOperation>();public void RemoveABRequest(string abname){string url = basePath + abname;ABRequestOpera[url].webRequest.Dispose();//试试多个异步创建ABRequestOpera.Remove(url);}async UniTask<AssetBundle> DownloadABPackage(string abname){if (cachedLoadedDic.ContainsKey(abname)){cachedLoadedDic[abname].AddRefer();return cachedLoadedDic[abname].GetAssetBundle();}string url = basePath + abname;Debug.Log(url);if (!cachedLoadingDic.ContainsKey(abname)){cachedLoadingDic.Add(abname, new LoadingAssetBundle(abname));}else{cachedLoadingDic[abname].AddRealLoadedTimesInLoading();}if (!ABRequestOpera.ContainsKey(url)){UnityWebRequest req = UnityWebRequestAssetBundle.GetAssetBundle(url);UnityWebRequestAsyncOperation operation = req.SendWebRequest();ABRequestOpera.Add(url, operation);}await ABRequestOpera[url];if (!cachedLoadedDic.ContainsKey(abname)){curReferIndexOrder++;AssetBundle ab = DownloadHandlerAssetBundle.GetContent(ABRequestOpera[url].webRequest);long size = long.Parse(ABRequestOpera[url].webRequest.GetResponseHeader("Content-Length"));cachedLoadedDic.Add(abname, new LoadedAssetBundle(abname,ab, size, curReferIndexOrder));}if (cachedLoadingDic.ContainsKey(abname)&&cachedLoadingDic[abname].GetRealLoadedTimesInLoading() > 0){cachedLoadedDic[abname].AddRefer();cachedLoadingDic[abname].ReduceRealLoadedTimesInLoading();if (cachedLoadingDic[abname].GetRealLoadedTimesInLoading() == 0){cachedLoadingDic.Remove(abname);}}    return cachedLoadedDic[abname].GetAssetBundle();}//所有包卸载public void UnLoadAll(){AssetBundle.UnloadAllAssetBundles(false);//注意清空缓存cachedLoadedDic.Clear();cachedLoadingDic.Clear();mainAB = null;mainManifest = null;}}

3..打包AB包代码

using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Collections.Generic;/// <summary>
/// AB包创建
/// </summary>
public class CreateAssetBundles : MonoBehaviour
{public static string BuildAssetBundlePath = Application.dataPath + "/AssetsPach/AssetBundles";[MenuItem("Build/BuildAssetBundles")]public static void BuildAssetBundle(){SetAssetBundle();string dir = BuildAssetBundlePath; //相对路径if (!Directory.Exists(dir))   //判断路径是否存在{Directory.CreateDirectory(dir);}BuildPipeline.BuildAssetBundles(dir, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget); //这里是第一点注意事项,BuildTarget类型选择WebGLAssetDatabase.Refresh();Debug.Log("打包完成");}//需要打包的资源目录public static string SetAssetBundlePath = Application.dataPath + "/AssetsPach/WortAsset";public static void SetAssetBundle(){string dir = SetAssetBundlePath; //相对路径AssetDatabase.RemoveUnusedAssetBundleNames();//移除无用的AssetBundleName//Debug.LogError(Application.dataPath);//上级路径 F:/TUANJIEProject/My project/Assetslist_Files = new List<stru_FileInfo>();ContinueCheck(dir);for (int a = 0; a < list_Files.Count; a++)//{SetBundleName(list_Files[a].assetPath);}Debug.Log("生成ab包完成");//SetBundleName("Assets/Ship/AC_Enterprise_T01/prefab/AC_Enterprise_T01_M01_ShipMesh.prefab");}//******资源参数static List<stru_FileInfo> list_Files;//文件列表static string assetBundleName = "ab";static string assetBundleVariant = "";//int indentation;//缩进等级struct stru_FileInfo{public string fileName;public string filePath;//绝对路径public string assetPath;//U3D内部路径public Type assetType;}static void ContinueCheck(string path){DirectoryInfo directory = new DirectoryInfo(path);FileSystemInfo[] fileSystemInfos = directory.GetFileSystemInfos();//获取文件夹下的文件信息foreach (var item in fileSystemInfos){int idx = item.ToString().LastIndexOf(@"\");string name = item.ToString().Substring(idx + 1);if (!name.Contains(".meta"))//剔除meta文件{CheckFileOrDirectory(item, path + "/" + name);}}}static void CheckFileOrDirectory(FileSystemInfo fileSystemInfo, string path){FileInfo fileInfo = fileSystemInfo as FileInfo;if (fileInfo != null){stru_FileInfo t_file = new stru_FileInfo();t_file.fileName = fileInfo.Name;t_file.filePath = fileInfo.FullName;t_file.assetPath = "Assets" + fileInfo.FullName.Replace(Application.dataPath.Replace("/", "\\"), "");//用于下一步获得文件类型t_file.assetType = AssetDatabase.GetMainAssetTypeAtPath(t_file.assetPath);list_Files.Add(t_file);}else{ContinueCheck(path);}}static void SetBundleName(string path){print(path);var importer = AssetImporter.GetAtPath(path);string[] strs = path.Split(".");string[] dictors = strs[0].Split('/');if (importer){if (assetBundleVariant != ""){importer.assetBundleVariant = assetBundleVariant;}if (assetBundleName != ""){importer.assetBundleName = path.ToLower() + "." + assetBundleName;}}else{Debug.Log("importer是空的" + path);//jpg  png tga}}}

4.资源如下 几张美女壁纸,每个预设都是一个壁纸和关闭按钮界面挂载了代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Panel : MonoBehaviour
{public string asssetName;// Start is called before the first frame updatevoid Start(){transform.GetComponentInChildren<Button>().onClick.AddListener(() => {//StartCoroutine(TestLoadSize();UIManager.Instance.DeletePanel(this);});}// Update is called once per framevoid Update(){}
}

4.启动场景和代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class UIManager :  MonoSingleton<UIManager>
{public Transform parent;// Start is called before the first frame updatevoid Start(){for (int i = 0; i < transform.childCount; i++){int index = i;transform.GetChild(i).GetComponent<Button>().onClick.AddListener(() => {//StartCoroutine(TestLoadSize();print(111);DownPanel($"Assets/Assetspach/wortasset/prefabs/Panel{index + 1}.prefab");//DownPanel($"Assets/Assetspach/wortasset/prefabs/Panel{index + 1}.prefab");});}}async void DownPanel(string asssetName){GameObject go = await ABManager.Instance.LoadAsset(asssetName);GameObject.Instantiate(go, parent).GetComponent<Panel>().asssetName =asssetName;}// Update is called once per framepublic  void DeletePanel(Panel panel){ABManager.Instance.ReduceRefer(panel.asssetName);DestroyImmediate(panel.gameObject);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/545030.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SQLite数据库使用指南以及相关API编程

SQLite介绍 SQLite是一种基于C语言开发的轻量级、快速、自包含、高可靠性和全功能的SQL数据库引擎。它是全球范围内使用最为广泛的数据库引擎&#xff0c;被嵌入到所有移动设备和大部分计算机中&#xff0c;并且伴随着无数日常使用的应用程序一起提供。SQLite的文件格式具有稳…

Qt教程 — 3.4 深入了解Qt 控件:Input Widgets部件(3)

目录 1 Input Widgets简介 2 如何使用Input Widgets部件 2.1 Dial 组件-模拟车速表 2.2 QScrollBar组件-创建水平和垂直滚动条 2.3 QSlider组件-创建水平和垂直滑动条 2.4 QKeySequenceEdit组件-捕获键盘快捷键 Input Widgets部件部件较多&#xff0c;将分为三篇文章介绍…

JavaWeb笔记 --- 四、HTMlCSS

四、HTMl&CSS HTML入门 基本标签 图片、音频、视频标签 尺寸单位 px&#xff1a;像素 百分比 超链接标签 列表标签 表格标签 布局标签 表单标签 CSS导入方式 CSS选择器

【JDBC编程】 Java程序操作数据库

目录 一、数据库编程的必备条件 二、什么是JDBC&#xff1f; 三、JDBC的使用 1. 准备工作 2. 建立数据库连接 2.1 加载驱动程序 2.2 数据库连接池技术 3. 正式操作 四、JDBC的局限性与MyBatis的优势 一、数据库编程的必备条件 编程语言&#xff0c;如Java&#xff0…

MySQL:SQL优化

1. 插入优化 使用insert语句单条单条数据插入效率偏低&#xff0c;建议使用insert批量插入数据&#xff0c;批量控制在500-1000条数据较为合适&#xff0c;当面对数以百万的数据时&#xff0c;可以使用load指令&#xff0c;提升插入数据效率 相关指令 #客户端连接服务端加上参…

哔哩哔哩后端Java一面

前言 作者&#xff1a;晓宜 个人简介&#xff1a;互联网大厂Java准入职&#xff0c;阿里云专家博主&#xff0c;csdn后端优质创作者&#xff0c;算法爱好者 最近各大公司的春招和实习招聘都开始了&#xff0c;这里分享下去年面试B站的的一些问题&#xff0c;希望对大家有所帮助…

稀碎从零算法笔记Day19-LeetCode:相交链表

题型&#xff1a;链表基本操作 链接&#xff1a;160. 相交链表 - 力扣&#xff08;LeetCode&#xff09; 来源&#xff1a;LeetCode 题目描述 给你两个单链表的头节点 headA 和 headB &#xff0c;请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点&…

AI - 支持向量机算法

&#x1f9e8;概念 支持向量机&#xff08;Support Vector Machine, SVM&#xff09;是一种强大的机器学习算法&#xff0c;主要用于解决二分类问题。 SVM的核心思想是找到一个超平面&#xff0c;这个超平面能够最好地将数据分为两类&#xff0c;即在保证分类准确的情况下&am…

AcWing 2. 01背包问题

题目描述 解题思路&#xff1a; 相关代码&#xff1a; import java.util.Scanner; public class Main {public static void main(String[] args){Scanner scanner new Scanner(System.in);/** 背包问题的物品下标最好从1开始。* *//*定义一f[i][j]数组&#xff0c;i表示的…

Go——运算符,变量和常量,基本类型

一.运算符 Go语言内置的运算符有&#xff1a; 算术运算符 关系运算符 逻辑运算符 位运算符 赋值运算符 1.1 算术运算符 注意&#xff1a;(自增)和--(自减)在go语言中是单独的语句&#xff0c;并不是运算符。 1.2 关系运算符 1.3 逻辑运算符 1.4 位运算符 位运算符对整数在内存…

202206青少年软件编程(图形化) 等级考试试卷(二级)

青少年软件编程(图形化) 等级考试试卷(二级)2022年6月 第1题:【 单选题】 角色初始位置如图所示,下面哪个选项能让角色移到舞台的左下角? ( ) A: B: C: D: 【正确答案】: C 【试题解析】 : 舞台的左下角, 坐标 x 为负数, 坐标 y 为负数, 故应该使用移…

在pzp203上运行ad9361 no-os工程

0. 环境 - pzp203 - ubuntu18 vivado2018 pzp203是一款plutosdr的国产兼容版。出厂默认是基于linux系统的&#xff0c;用libiio调用。软硬件兼容adalm-pluto。开发板提供网盘资料&#xff0c;是添加了板卡适配的。 1. hdl 1.1 准备源码 hdl https://github.com/analogdevi…