63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
using UnityEngine.Networking;
|
||
using System.Threading.Tasks;
|
||
using System;
|
||
|
||
|
||
public class ImageLoader : MonoBehaviour
|
||
{
|
||
// 缓存字典
|
||
private Dictionary<string, Sprite> imageCache = new Dictionary<string, Sprite>();
|
||
public Sprite sprite;
|
||
// 异步加载图片
|
||
public async Task<Sprite> LoadImageAsync(string url)
|
||
{
|
||
if (!IsValidUrl(url))
|
||
{
|
||
return sprite;
|
||
}
|
||
// 如果缓存中已经有图片,则直接返回缓存的图片
|
||
if (imageCache.ContainsKey(url))
|
||
{
|
||
return imageCache[url];
|
||
}
|
||
|
||
// 如果缓存中没有图片,则异步加载
|
||
using (UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(url))
|
||
{
|
||
// 发送请求并等待响应
|
||
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 sprite;
|
||
}
|
||
}
|
||
}
|
||
// 将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 static bool IsValidUrl(string url)
|
||
{
|
||
Uri uriResult;
|
||
return Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
|
||
}
|
||
}
|