Search code examples
c#unity3d-2dtools

How to load an image from URL with Unity?


Please save me from going crazy.

No matter how many times I google, I always end up with (usually deprecated) versions of the following code:

IEnumerator setImage(string url) {
    Texture2D texture = profileImage.canvasRenderer.GetMaterial().mainTexture as Texture2D;

    WWW www = new WWW(url);
    yield return www;

    Debug.Log("Why on earh is this never called?");

    www.LoadImageIntoTexture(texture);
    www.Dispose();
    www = null;
}

I'm using Unity 5 not 4. The URL I'm trying to load exists. Please shine some light on me.

How do I load an image over HTTP and display it in a UnityEngine.UI.Image?


Solution

  • quick clarification: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

    public void yourMethod()
    {
       StartCoroutine(setImage("http://url/image.jpg")); //balanced parens CAS
    }
    
    IEnumerator setImage(string url) {
        Texture2D texture = profileImage.canvasRenderer.GetMaterial().mainTexture as Texture2D;
    
        WWW www = new WWW(url);
        yield return www;
    
        // calling this function with StartCoroutine solves the problem
        Debug.Log("Why on earh is this never called?");
    
        www.LoadImageIntoTexture(texture);
        www.Dispose();
        www = null;
    }