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);