【Unity使用addressables做资源热更,在不重启应用的情况下实时更新资源】

该代码示例展示了在Unity中如何使用Addressables系统进行资源的异步加载和释放,特别是动态新增资源和更新资源目录的方法。当替换新资源时,需要先释放旧资源,然后加载新资源,同时处理加载失败的情况。文章还提到了远程加载路径的设置和清除依赖缓存的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码

示例代码如下:`.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class AddressableMain : MonoBehaviour
{
    public Button btn;
    public InputField inp;

    public RawImage img;
    public Button freeResBtn;
    public Texture2D tex2D;

    private AsyncOperationHandle<Texture2D> handle;
    private AsyncOperationHandle<GameObject> handle1;

    private GameObject gam;
    void Start()
    {
        btn.onClick.AddListener(() => BtnClick(inp.text));
        freeResBtn.onClick.AddListener(() => BtnShif(inp.text));
    }
    
    private void BtnClick(string name)
    {

        //handle = Addressables.LoadAssetAsync<Texture2D>(name);
        //handle.Completed += OnLoadCompleted;


        //不能用这个方式加载,用它加载不能完全释放不能动态新增资源
        //Addressables.LoadAssetAsync<GameObject>(name).Completed += (obj) =>
        //{
        //    gam = obj.Result;
        //    Instantiate(gam);
        //};

        //用这个方式加载资源
        handle1 = Addressables.LoadAssetAsync<GameObject>(name);
        handle1.Completed += OnLoadCompleted1;
    }
    void OnLoadCompleted(AsyncOperationHandle<Texture2D> obj)
    {
        if (obj.Status == AsyncOperationStatus.Succeeded)
        {
            tex2D = obj.Result;
            img.texture = tex2D;
        }
        else
        {
            Debug.LogError("Failed to load asset: " + obj.OperationException.ToString());
        }

    }

    void OnLoadCompleted1(AsyncOperationHandle<GameObject> obj)
    {
        if (obj.Status == AsyncOperationStatus.Succeeded)
        {
            gam = obj.Result;
            Instantiate(gam);
        }
        else
        {
            Debug.LogError("Failed to load asset: " + obj.OperationException.ToString());
        }

    }


    private void BtnShif(string name)
    {
        StartCoroutine(gengxindizhi(name));
    }

    public IEnumerator gengxindizhi(string name)
    {
        //重点就是下面这个方法重新加载资源列表
        yield return UpdateCatalog(name);

        Addressables.Release(handle1);

        if(gam!=null)
           Addressables.Release(gam);

        //这个方法是释放缓存
        Addressables.ClearDependencyCacheAsync(name);
    }

}

新加代码在不同路径下的资源加载不同的catalog去定位资源:

private IEnumerator UpdateCatalog(string name)
{
    string themeName = name;
    int index = name.IndexOf('_');
    if (index >= 0)
    {
        themeName = name.Substring(0, index);
    }
    string catalogPath = themeName + "/catalog.json";
    if (!File.Exists(catalogPath))
    {
    //没有加加载默认路径的
        catalogPath = "catalog.json";
    }
    
    Debug.Log(string.Format("addressablecatalogs::::::" + catalogPath));
    //清楚资源定位器
    Addressables.ClearResourceLocators();
    //异步加载内容
    var catalogHandle = Addressables.LoadContentCatalogAsync(catalogPath, false);
    //等待加载完成
    catalogHandle.WaitForCompletion();

//方法用于检查是否有可用的地址目录更新
    AsyncOperationHandle<List<string>> checkHandle = Addressables.CheckForCatalogUpdates(false);
    yield return checkHandle;

    if (checkHandle.Status == AsyncOperationStatus.Succeeded)
    {
        List<string> catalogs = checkHandle.Result;
        if (catalogs != null && catalogs.Count > 0)
        {
            var updateHandle = Addressables.UpdateCatalogs(catalogs, false);
            yield return updateHandle;

            Debug.Log("获取更新完成!");
        }
        else
        {
            Debug.Log("不需要更新!");
        }
    }
    else
    {
        Debug.Log("获取更新失败!");
    }
    Addressables.Release(checkHandle);
}

替换新资源后,先释放,在加载新资源就能成功了。

请添加图片描述
这里crc的设置要改

remoteloadpath路径要输入这个http://[PrivateIpAddress]:[HostingServicePort]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值