How to download image using javascript in Unity WebGL

1.4k views Asked by At

I'm trying to download image from a server to my Unity WebGL app. I used WWW and it works but it has problems where it freezes the whole WebGL app in the browser while its downloading. This simple code works, but it stops the app while its download the image.

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

I already exhausted all possibilities of using Unity to download the image, since it either freeze or dont work,

Instead, I want to see if its possible to for unity to tell the browser to download the image for me using javascript, then have it pass that image back to my unity c# code somehow.

Anybody know how to do that using external java script? I know it can do it because I have code that can send a picture from Unity to the server using external java script and it works without freezing the app, so it must can work the other way also.

Thanks!

1

There are 1 answers

7
Programmer On

I haven't seen instance of WWW freezing in WebGL build. You are likely doing something wrong and the two lines of code in your question cannot be used to tell what the problem is.

If the WWW API is indeed the problem then use UnityWebRequest. There is no need to use Javascript for this.

void Start()
{
    StartCoroutine(downloadTexture("http://www.myUrl.png"));
}

IEnumerator downloadTexture(string url)
{
    using (UnityWebRequest www = UnityWebRequest.GetTexture(url))
    {
        yield return www.Send();

        if (www.isError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Texture myTexture = DownloadHandlerTexture.GetContent(www);
        }
    }
}