iT邦幫忙

2024 iThome 鐵人賽

DAY 23
0
Software Development

Unity黑科技揭秘:30個專業遊戲開發者必知的開發技巧系列 第 23

Unity Sprites - 從網絡URL下載圖片在Image中顯示!

  • 分享至 

  • xImage
  •  

有時候我們需要從網絡讀取圖片
並且把下載的圖片顯示在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.");
        }
    }
}

上一篇
Unity Plugins - 如何發佈一款Unity Asset Store插件?
下一篇
Unity Imgur - 使用免費的Imgur API上傳圖片!
系列文
Unity黑科技揭秘:30個專業遊戲開發者必知的開發技巧25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言