UnityCommon/base/ImageLoader.cs
2024-12-04 02:09:23 +08:00

67 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using System.Threading.Tasks;
public class ImageLoader : MonoBehaviour
{
// 缓存字典
private Dictionary<string, Sprite> imageCache = new Dictionary<string, Sprite>();
//private async void Start()
//{
// GetComponent<Image>().sprite = await LoadImageAsync("https://fantasymonster-app.oss-cn-hangzhou.aliyuncs.com/goods/mall/c7860d8909194d479b6f27ccb922e863.png");
//}
// 异步加载图片
public async Task<Sprite> LoadImageAsync(string url)
{
// 如果缓存中已经有图片,则直接返回缓存的图片
if (imageCache.ContainsKey(url))
{
Debug.Log("Image found in cache.");
return imageCache[url];
}
// 如果缓存中没有图片,则异步加载
using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
{
// 等待请求完成
//await webRequest.SendWebRequest().ToTask();
// 发送请求并等待响应
var operation = webRequest.SendWebRequest();
while (!operation.isDone)
await Task.Yield(); // 等待请求完成使用await以非阻塞的方式处理
// 检查请求是否成功
if (webRequest.result == UnityWebRequest.Result.Success)
{
// 获取下载的纹理
Texture2D texture = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
// 将纹理缓存
imageCache[url] = TextureToSprite(texture);
return imageCache[url];
}
else
{
Debug.LogError("Failed to load image: " + webRequest.error);
return null;
}
}
}
// 将Texture2D转换为Sprite
Sprite TextureToSprite(Texture2D texture)
{
// 使用纹理的尺寸创建一个Sprite
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
// 加载并显示图片
//public async void LoadAndDisplayImage(string url, Renderer renderer)
//{
// Texture2D texture = await LoadImageAsync(url);
// if (texture != null)
// {
// renderer.material.mainTexture = texture;
// }
//}
}