imageunity-game-engineloadimage

Unity - Loading image using www cause all images in application to change


I am pretty new to Unity, so this might be an easy one.

I am trying to load and image from a URL an into an image in my application. In my application I have many different images, but for some reason all the images change to the image loaded from my url.

I have made a component called LoadImage and added it only to the one image I want to change. My code for loading the image looks like this:

public class LoadImage : MonoBehaviour 
{

    public Image img; 

    // Use this for initialization
    void Start () 
    {
        DownloadViaURL();
    }

    void DownloadViaURL()
    {
        Debug.Log("Called DownloadViaURL");
        FirebaseDatabase.DefaultInstance
           .GetReference("Child1").Child("Child2").Child("ImageURL")
           .GetValueAsync().ContinueWith(task => 
           {
               Debug.Log("Default Instance entered");
               if (task.IsFaulted)
               {
                   Debug.Log("Error retrieving data from server");
               }
               else if (task.IsCompleted)
               {
                   DataSnapshot snapshot = task.Result;

                   string data_URL = snapshot.GetValue(true).ToString();

                   //Start coroutine to download image
               StartCoroutine(AccessURL(data_URL));
               }
           });
    }

    IEnumerator AccessURL(string url)
    {
        using (WWW www = new WWW(url))
        {
            yield return www;
                 www.LoadImageIntoTexture(img.mainTexture as Texture2D);
            Debug.Log("Texture URL: " + www.url);
        }
    }  
}

And I have then added the image as the public Image img;

Can anyone tell my why unity load the image into all imageviews in my application instead of just the one?


Solution

  • You say

    I have many different images,

    but I guess you mean different Image components where you very probably referenced the same texture from your assets multiple times

    So what your code actually does is overwriting whatever texture asset is referenced by your image => it is also changed in all other images/materials etc that reference the same texture asset.

    You should rather create a new texture, load the data into it and change the image's texture reference:

    // Create new texture
    // Size values don't matter because texture will be overwritten
    var newTexture = new Texture2D(2,2);
    
    // Load image I new texture
    www.LoadImageToTexture(newTexture);
    
    // Use the reference to that new texture
    img.mainTexture = newTexture;