有時候我們需要從網絡讀取圖片
並且把下載的圖片顯示在Image的Sprite之中
這時候可以寫一個通用的static代碼
方便任何新的專案快速使用
public static class SpritesUtility
{
public static byte[] ToBytes(this Sprite sprite)
{
return sprite.texture.EncodeToPNG();
}
public static Sprite ToSprite(this byte[] bytes)
{
var texture = new Texture2D(10, 10);
texture.LoadImage(bytes);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
public static void DownloadImageFromURL(string imageURL, System.Action<byte[]> onImageDownloaded)
{
CoroutineManager.Instance.StartCoroutine(DownloadImageFromURLCoroutine(imageURL, onImageDownloaded));
}
private static IEnumerator DownloadImageFromURLCoroutine(string imageURL, System.Action<byte[]> onImageDownloaded)
{
string cacheBusterURL = imageURL + (imageURL.Contains("?") ? "&" : "?") + "nocache=" +
System.DateTime.Now.Ticks;
using UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(cacheBusterURL);
webRequest.SetRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");
webRequest.SetRequestHeader("Pragma", "no-cache");
webRequest.SetRequestHeader("Expires", "0");
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.Success)
{
byte[] imageData = ((DownloadHandlerTexture)webRequest.downloadHandler).data;
onImageDownloaded?.Invoke(imageData);
}
else
{
Debug.LogWarning($"Error downloading image from URL: {imageURL} - {webRequest.error}");
onImageDownloaded?.Invoke(null);
}
}
}
這個要搭配Coroutine Manager 使用才行:
public class CoroutineManager : MonoBehaviour
{
private static CoroutineManager instance;
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(gameObject);
return;
}
instance = this;
}
public static CoroutineManager Instance
{
get
{
if (instance == null)
{
GameObject singletonObject = new GameObject();
instance = singletonObject.AddComponent<CoroutineManager>();
singletonObject.name = "CoroutineManagerSingleton";
}
return instance;
}
}
public static void Trigger(IEnumerator method)
{
Instance.StartCoroutine(method);
}
}
使用方法:
public class ImageLoader : MonoBehaviour
{
public string imageURL = "https://example.com/image.png";
public SpriteRenderer spriteRenderer;
void Start()
{
SpritesUtility.DownloadImageFromURL(imageURL, OnImageDownloaded);
}
void OnImageDownloaded(byte[] imageData)
{
if (imageData != null)
{
Sprite sprite = imageData.ToSprite();
spriteRenderer.sprite = sprite;
}
else
{
Debug.LogError("Failed to download image.");
}
}
}