Super simple way to load any image from URL and show it as a UI Image in Unity



Hey dude, here I’m going to share a simple script to load any image you can have from URL accross internet and show it as a UI Image inside your Unity game.

Create a script name it UiImageFromUrl.cs and copy and paste the script content below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;

public class UiImageFromUrl : MonoBehaviour
{
	
	public string imageUrl = "https://ciihuy.com/wp-content/uploads/2019/03/icon.jpg";
	
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(GetImage(imageUrl));
    }

    // Update is called once per frame
    void Update()
    {
        
    }
	
	IEnumerator GetImage(string imageUrl)
    {
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(imageUrl);
        yield return request.SendWebRequest();
        if (request.isNetworkError || request.isHttpError)
            Debug.Log(request.error);
        else{
			Texture2D downloadedTexture = DownloadHandlerTexture.GetContent(request) as Texture2D;
			GetComponent<Image>().sprite = Sprite.Create(downloadedTexture, new Rect(0, 0, downloadedTexture.width, downloadedTexture.height), new Vector2(0, 0));
		}
    }
}

Then attach the script to a UI Image object inside your Unity game canvas. Go to inspector, set the url of the texture. That’s all, run the game and you will see the image loaded.

loading...

Leave a Reply

Your email address will not be published. Required fields are marked *