可寻址系统 动态加载单个资源-管理器

异步加载资源

public void LoadAssetAsync<T>(string name, Action<AsyncOperationHandle<T>> callBack)
{
    
    
    //名称和类型作为key 解决资源同名问题
    string keyName = name + "_" + typeof(T).Name;
    AsyncOperationHandle<T> handle;
    if (resDic.ContainsKey(keyName))
    {
    
    
        handle = (AsyncOperationHandle<T>)resDic[keyName];     //异步加载的返回值
        if (handle.IsDone)//异步加载完成
            callBack(handle);//回调            
        else//资源仍在加载
        {
    
    
            handle.Completed += (obj) =>
            {
    
    
                if (obj.Status == AsyncOperationStatus.Succeeded)
                    callBack(obj);
            };
        }
    }
    else//异步加载
    {
    
    
        handle = Addressables.LoadAssetAsync<T>(name);
        handle.Completed += (obj) =>
        {
    
    
            if (obj.Status == AsyncOperationStatus.Succeeded)
                callBack(obj);
            else
            {
    
    
                Debug.LogWarning(keyName + "资源加载失败");
                if (resDic.ContainsKey(keyName))
                    resDic.Remove(keyName);//异步加载  执行晚于字典添加 
            }
        };
        resDic.Add(keyName, handle);
    }
}

资源释放

    public void Release<T>(string name)
    {
    
    
        string keyName = name + typeof(T).Name;
        if (resDic.ContainsKey(keyName))
        {
    
    
            AsyncOperationHandle<T> handle = (AsyncOperationHandle<T>)resDic[keyName];
            Addressables.Release(handle);
            resDic.Remove(keyName);
        }
    }

资源清空

    public void Clear()
    {
    
    
        resDic.Clear();
        AssetBundle.UnloadAllAssetBundles(true);
        Resources.UnloadUnusedAssets();
        GC.Collect();
    }

其他

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
public class AddressableMgr
{
    
    
    private static AddressableMgr instance = new AddressableMgr();
    public static AddressableMgr Instance => instance;
    private AddressableMgr() {
    
     }
    public Dictionary<string, IEnumerator> resDic = new Dictionary<string, IEnumerator>();
    //异步加载
    public void LoadAssetAsync<T>(string name, Action<AsyncOperationHandle<T>> callBack)
    {
    
    	}
    //释放资源
    public void Release<T>(string name)
    {
    
    	}
    //清空资源
    public void Clear()
    {
    
    	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43796392/article/details/123041828