Unity-使用www加载图像会导致应用程序中的所有图像发生更改

时间:2019-01-03 20:51:20

标签: image unity3d loadimage

我是Unity新手,所以这可能很简单。

我正在尝试从URL中加载图像并将其成像到应用程序中的图像中。在我的应用程序中,我有许多不同的图像,但是由于某种原因,所有图像都更改为从我的URL加载的图像。

我制作了一个名为LoadImage的组件,并将其仅添加到我要更改的一个图像中。我用于加载图像的代码如下:

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);
        }
    }  
}

然后我将该图像添加为公共图像img;

谁能告诉我为什么统一将图像加载到我的应用程序中的所有图像视图中,而不只是一个图像?

1 个答案:

答案 0 :(得分:1)

您说

  

我有很多不同的图像,

但是我想您指的是不同的Image组件,您很可能多次引用了资产中的相同纹理

因此,您的代码实际执行的操作是覆盖图像引用的任何纹理资产=>在引用相同纹理资产的所有其他图像/材质等中,它也会更改。

您应该创建一个新纹理,将数据加载到其中并更改图像的纹理参考:

// 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;