【问题标题】:Unity - Loading image using www cause all images in application to changeUnity - 使用 www 加载图像会导致应用程序中的所有图像发生变化
【发布时间】:2019-01-03 20:51:20
【问题描述】:

我对 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;

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

【问题讨论】:

  • 可能是因为您使用的是同一个目标 Texture2D?

标签: image unity3d loadimage


【解决方案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;

【讨论】:

  • 哦,我明白你的意思了,我认为你是对的!但我在最后一行收到错误:“无法将属性或索引器 Image.mainTexture 分配给 --- 它是只读的”-我已经尝试过 material.mainTexture 但这给了我与开始时相同的问题(加载所有图像组件中的图像)
  • 没关系 - 通过创建一个 Sprite 来解决它。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多