1、什么是引用计数规则?
当通过加载使用可寻址资源时,Addressables会在内部帮助我们进行引用计数,使用资源时,引用计数+1,释放资源时,引用计数-1,当可寻址资源的引用为0时,就可以卸载它了
为了避免内存泄露(不需要使用的内容残留在内存中),我们要保证加载资源和卸载资源是配对使用的
注意:释放的资源不一定立即从内存中卸载,在卸载资源所属的AB包之前,不会释放资源使用的内存(比如自己所在的AB包 被别人使用时,这时AB包不会被卸载,所以自己还在内存中),我们可以使用Resources.UnloadUnusedAssets卸载资源(建议在切换场景时调用)
AB包也有自己的引用计数(Addressables把它也视为可寻址资源)从AB包中加载资源时,引用计数+1,从AB包中卸载资源时,引用计数-1,当AB包引用计数为0时,意味着不再使用了,这时会从内存中卸载
总结:Addressables内部会通过引用计数帮助我们管理内存,我们只需要保证 加载和卸载资源配对使用即可
2、AddressableMgr
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using NUnit.Framework;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AddresssablesInfo
{
public AsyncOperationHandle handle;
public uint count;
public AddresssablesInfo(AsyncOperationHandle handle)
{
this.handle = handle;
count += 1;
}
}
public class AddressableMgr
{
public static AddressableMgr instance = new AddressableMgr();
public static AddressableMgr Instance => instance;
// 有一个容帮助存储异步加载的返回值
public Dictionary<string, AddresssablesInfo> resDic = new Dictionary<string, AddresssablesInfo>();
private AddressableMgr() { }
public void LoadAssetAsync<T>(string name, Action<AsyncOperationHandle<T>> callback)
{
//

最低0.47元/天 解锁文章
2169

被折叠的 条评论
为什么被折叠?



