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

直接上代码

示例代码如下:`.

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)
    {
    
    
        //重点就是下面这个方法重新加载资源列表
        AsyncOperationHandle<List<IResourceLocator>> h = Addressables.UpdateCatalogs();
        yield return h;

        Addressables.Release(handle1);

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

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

}

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

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

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

猜你喜欢

转载自blog.csdn.net/CPCM_VN/article/details/130811961