Load Image From URL In Unity

In this article, we will see how you can load image from url in unity. By the end of this article you will be able to load sprite or PNG/JPG from any server URL.

Load image from url in unity

You load image from url in unity using UnityWebRequestTexture. Let’s Look at the code.

Load Image From URL In Unity

 public IEnumerator LoadImageFromURL(string url)
    {
        UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            Texture2D texture = ((DownloadHandlerTexture)www.downloadHandler).texture;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2());
            yourImage.sprite = sprite;
        }
    }

We have successfully loaded the sprite and texture both. 

Let’s Understand the code.

  • First, on line 3,  we loaded the texture using UnityWebRequestTexture. UnityWebRequestTexture is a UnityWebRequest that is appropriately configured to download an image from the URL as a texture.
  • Then on line 4, We waited for the web call to get completed.
  • Then we just check if there are any errors or not.
  • On line 12, We got Texture2D from the DownloadHander. We also type-casted it to DownloadHandlerTexture, because unlike UnityWebRequest UnityWebRequestTexuture holds the data into DownloadHandlerTexure
  • On line number 13, we converted the texture into the sprite.
  • Finally, you can use this sprite in your image. As you can see on line 14.

Hope this code breakdown will help you, especially if you are a beginner. Hope this article was helpful. Please Comment down your thoughts.

Recommended Posts

2 thoughts on “Load Image From URL In Unity”

  1. You can call this coroutine like this:

    string _url = “https://gamedevsolutions.com/wp-content/uploads/2022/02/Logo-min.png”;
    StartCoroutine(LoadImageFromURL(_url));

    Thank you for your comment. Let me know if you still have any doubts.

Leave a Comment

Your email address will not be published.