Search Unity

Question Fastest way to load a texture (WebGL)

Discussion in 'Web' started by Kloper, May 13, 2020.

  1. Kloper

    Kloper

    Joined:
    Jan 28, 2014
    Posts:
    93
    I am working on a WebGL project where I have to load some high resolution textures based on users choice.
    Since each file is around 2mb and there is around 40 of them, I dont wanna preload all of them. So what would be the best way to do this?

    Unity documentation suggests asset bundles, but I assume thats only because they can be used for all kind of things... not sure if thats the best option when it comes to simple textures?
     
  2. iMancha

    iMancha

    Joined:
    Sep 22, 2014
    Posts:
    25
    Code (CSharp):
    1.  
    2.  
    3. public int imageId;
    4.  
    5. public struct Image
    6. {
    7.     //images
    8.     public Sprite Image;
    9.     public string ImageUrl;
    10.     public int ImageId;
    11. }
    12.  
    13.     public void LoadImages(int id)
    14.     {
    15.         imageId= id;
    16.         StartCoroutine(GetImages());
    17.     }
    18.  
    19. IEnumerator GetImages()
    20.         {
    21.             for (int i = 0; i < allImages.Length; i++)
    22.             {
    23.                 if (allImages[i].ImageId == imageId)
    24.                 {
    25.                     UnityWebRequest image = UnityWebRequestTexture.GetTexture(allImages[i].ImageURL);
    26.                     yield return image.SendWebRequest();
    27.  
    28.                     if (image.isNetworkError || image.isHttpError)
    29.                     {
    30.                         Debug.Log(image.error);
    31.                         allImages[i].Image = defaultImage; //use a placeholder image in case the remote image does not load
    32.                     }
    33.                     else
    34.                     {
    35.                         if (image.isDone)
    36.                         {
    37.                             Texture2D tx = ((DownloadHandlerTexture)image.downloadHandler).texture;
    38.                             allImages[i].Image = Sprite.Create(tx, new Rect(0f, 0f, tx.width, tx.height), Vector2.zero, 100f);                      
    39.                         }
    40.                     }
    41.                 }
    42.             }      
    43.         }
    44.