Search Unity

Write a blocking UnityWebRequest deliberately (for educational purpose)

Discussion in 'Scripting' started by MiguelOscarGarcia, Jan 7, 2020.

  1. MiguelOscarGarcia

    MiguelOscarGarcia

    Joined:
    Oct 19, 2019
    Posts:
    8
    Hi all, I wanted to write a method that blocks the UI while downloading an image through a UnityWebRequest but I can't get it working.

    Here is the code:
    Code (CSharp):
    1. public void LoadImage()
    2.     {
    3.         using (UnityWebRequest httpClient = new UnityWebRequest("https://spdvistorage.blob.core.windows.net/clickycrates-blobs/default/4-2-pokemon-transparent.png"))
    4.         {
    5.             Debug.Log("Getting image...");
    6.             httpClient.downloadHandler = new DownloadHandlerTexture();
    7.             httpClient.SendWebRequest(); // blocking call?
    8.             while (httpClient.downloadProgress < 1.0f)
    9.             {
    10.                 Thread.Sleep(100);
    11.                 Debug.Log(httpClient.downloadProgress * 100 + "% (Bytes downloaded: " + httpClient.downloadedBytes/1024 + " KB");
    12.             }
    13.             Thread.Sleep(1000);
    14.             Debug.Log("hpptClient.isDone = " + httpClient.isDone);
    15.             if (httpClient.isNetworkError || httpClient.isHttpError)
    16.             {
    17.                 Debug.Log(httpClient.error);
    18.             }
    19.             else
    20.             {
    21.                 Texture2D texture = DownloadHandlerTexture.GetContent(httpClient);
    22.                 image.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f);
    23.             }
    24.         }
    25.     }
    but I get an
    Code (csharp):
    1. InvalidOperationException: Cannot get content from an unfinished UnityWebRequest object
    in line
    Code (csharp):
    1. Texture2D texture = DownloadHandlerTexture.GetContent(httpClient);
    Also
    Code (csharp):
    1. Debug.Log("hpptClient.isDone = " + httpClient.isDone);
    returns false.

    Any hint on how could I achieve this?

    Of course the main goal is later convert this to a Coroutine to show the UI is still responding, but I'm specially interested first in showing how this call blocks the UI.

    Thanks in advance!
     
  2. Aurimas-Cernius

    Aurimas-Cernius

    Unity Technologies

    Joined:
    Jul 31, 2013
    Posts:
    3,732
    While download and most of texture creation happens on background thread, it is completed on main thread, so it is not possible to do this synchronously with DownloadHandlerTexture.
    Use DownloadHandlerBuffer and then use ImageConversion to make texture out of bytes.
     
    MiguelOscarGarcia likes this.
  3. MiguelOscarGarcia

    MiguelOscarGarcia

    Joined:
    Oct 19, 2019
    Posts:
    8
    Thanks a lot! That was what I was looking for!!!