unity异步加载导致图片不能被成功覆盖

unity中图片加载导致的异步问题由于重复调用Addreessable相关API且间隔时间太短导致图片不能正确显示

using UnityEngine;
using System.Collections;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class AssistImage : MonoBehaviour
{
    private Coroutine _loadCo;
    private AsyncOperationHandle loaderHandle;
    private Image img;
    Color32 color;

    private void Awake()
    {
        img = this.gameObject.GetComponent<Image>();
        color = this.img.color;
    }
    public void setAsyncImage(string path)
    {
        if (string.IsNullOrEmpty(path))
            return;

        if (_loadCo != null)
        {
            StopCoroutine(_loadCo);
            _loadCo = null;
        }
        if (loaderHandle.IsValid())
            AssetLoader.Instance.ReleaseAsset(loaderHandle);
        //没有激活会报协程的错
        if (!this.gameObject.activeSelf)
            return;



        loaderHandle = AssetLoader.Instance.LoadAssetReturnHandle<Sprite>(path, null);
        _loadCo = StartCoroutine(WaitForLoad());
    }

    IEnumerator WaitForLoad()
    {
        while (!loaderHandle.IsDone) // 检查操作是否完成
        {
            yield return null; // 等待下一帧
        }


        if (loaderHandle.Status == AsyncOperationStatus.Succeeded)
        {
            if (this != null)
            {
                setImg(loaderHandle.Result as Sprite);
            }
        }
        else if (loaderHandle.Status == AsyncOperationStatus.Failed)
        {
            // 加载失败,处理错误
            Debug.LogError("Failed to load asset: " + loaderHandle.OperationException);
        }
    }

    public void SetAlpha(byte a, bool now = true)
    {
        color.a = a;
        if (now)
        {
            this.img.color = color;
        }
    }

    public void setImg(Sprite sprite)
    { 
        this.img.sprite = sprite;
        SetAlpha(color.a);
    }

    public void setNaviteSize()
    {
        this.img.SetNativeSize();
    }

    void OnDestroy()
    {

        this.img.sprite = null;
        if (_loadCo != null)
            StopCoroutine(_loadCo);
        _loadCo = null;
        if (loaderHandle.IsValid())
        {
            this.img.sprite = null;
            AssetLoader.Instance.ReleaseAsset(loaderHandle);
        }
    }
}

上面是相关脚本,下方是是使用方法

        AssistImage bg = ui.m_bg.GetComponent<AssistImage>();
        if (bg == null)
        {
            bg = ui.m_bg.AddComponent<AssistImage>();
        }
        bg.setAsyncImage(currency.Bg);
        AssistImage icon = ui.m_Icon.GetComponent<AssistImage>();
        if (icon == null)
        {
            icon = ui.m_Icon.AddComponent<AssistImage>();
        }
        icon.setAsyncImage(currency.Image);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值