从 url 加载和显示图像

Dav*_*vid 3 c# url image unity-game-engine

我正在尝试将图像从 url 加载到 GameObject。

我找到了下一个教程:

https://www.youtube.com/watch?v=8UK2EsKBzv8

下载成功,但是看不到图片。

我究竟做错了什么?

// Use this for initialization
void Start () {
    StartCoroutine(loadSpriteImageFromUrl("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png"));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{
    // Check internet connection
    if (Application.internetReachability == NetworkReachability.NotReachable)
    {
        yield return null;
    }

    var www = new WWW(URL);
    Debug.Log("Download image on progress");
    yield return www;

    if (string.IsNullOrEmpty(www.text))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);                      
        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height),      
            Vector2.one / 2);                                     

        GetComponent<SpriteRenderer>().sprite = sprite;    // Change current sprite
    }
}
Run Code Online (Sandbox Code Playgroud)

跑步前 跑后

编辑

按照建议从 ScriptRenderer 移动到 UI Image 后,代码如下所示:

IEnumerator loadSpriteImageFromUrl(string URL, GameObject cell)
{
    // Check internet connection
    if(Application.internetReachability == NetworkReachability.NotReachable)
    {
        yield return null;
    }

    var www = new WWW(URL);
    Debug.Log("Download image on progress");
    yield return www;

    if(string.IsNullOrEmpty(www.text))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);                      
        Sprite sprite = Sprite.Create(texture, 
            new Rect(0,0, texture.width, texture.height),      
            Vector2.one/2);                                    

        cell.AddComponent<Image>();
        cell.GetComponent<Image>().sprite = sprite;    
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了屏幕上的下一个结果(而不是 url 中的图像):

在此处输入图片说明

Pro*_*mer 8

你的代码没问题。下载的图像未显示,因为您在场景视图中并且相机远离它。

在此处输入图片说明

选择脚本附加到的游戏对象,然后按F。它应该放大它,您将看到下载的图像。请参阅此处了解如何重置您的 Unity 布局以恢复游戏视图。

在此处输入图片说明



如果您仍然看不到图像,则说明该图像SpriteRenderer不在相机前。从截图来看,它的位置是0, 00所以请确保相机的位置是0, 0, -10

显示图像的正确方法:

要在 Unity 中简单地显示图像,请使用ImageRawImage组件。RawImage建议使用,因为它在更改纹理时不会产生垃圾。你应该已经知道如何从 th

如果您需要将 Rigidbody 或 2D Colliders 附加到该图像,则使用SpriteRendererMeshRenderer用于 3D 对象以显示image.

这是在 Unity 中显示图像的四种方式。如果根本不需要物理或碰撞,建议使用#2

1 .Image组件:

public Image imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height), Vector2.zero);

        imageToDisplay.sprite = sprite;
    }
}
Run Code Online (Sandbox Code Playgroud)

过去有问题LoadImageIntoTexture。出于这个原因,我的其他示例不会使用LoadImageIntoTexture. 如果您看到一个问号作为图像,则使用www.bytesTexture2D.LoadImage函数。

简单替换:

Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);
Run Code Online (Sandbox Code Playgroud)

Texture2D texture = new Texture2D(1, 1);
texture.LoadImage(www.bytes);
texture.Apply();
Run Code Online (Sandbox Code Playgroud)

2 .RawImage组件(推荐):

public RawImage imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        texture.LoadImage(www.bytes);
        texture.Apply();


        imageToDisplay.texture = texture;
    }
}
Run Code Online (Sandbox Code Playgroud)

3 .SpriteRenderer组件:

主要用于带有Rigidbody2D2D Colliders 的2D 对象和 2D 物理模拟。如果没有,则使用上面的 UI(#1#2)。

public SpriteRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        Sprite sprite = Sprite.Create(texture,
            new Rect(0, 0, texture.width, texture.height), Vector2.zero);


        imageToDisplay.sprite = sprite;
    }
}
Run Code Online (Sandbox Code Playgroud)

4 .MeshRenderer组件:

主要用于 3D 对象和带有Rigidbody2D Colliders 的3D 物理模拟。如果没有,则使用上面的 UI(#1#2)。只需使用带有MeshRenderer.

public MeshRenderer imageToDisplay;
string url = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png";

void Start()
{
    StartCoroutine(loadSpriteImageFromUrl(url));
}

IEnumerator loadSpriteImageFromUrl(string URL)
{

    WWW www = new WWW(URL);
    while (!www.isDone)
    {
        Debug.Log("Download image on progress" + www.progress);
        yield return null;
    }

    if (!string.IsNullOrEmpty(www.error))
    {
        Debug.Log("Download failed");
    }
    else
    {
        Debug.Log("Download succes");
        Texture2D texture = new Texture2D(1, 1);
        www.LoadImageIntoTexture(texture);

        imageToDisplay.material.mainTexture = texture;
    }
}
Run Code Online (Sandbox Code Playgroud)

新的统一版本:

WWWAPI似乎是现在的弃用。UnityWebRequest现在应该使用。

public Image imageToUpdate;

void Start()
{
    StartCoroutine(downloadImage());
}

IEnumerator downloadImage()
{
    string url = "http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg";

    UnityWebRequest www = UnityWebRequest.Get(url);

    DownloadHandler handle = www.downloadHandler;

    //Send Request and wait
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        UnityEngine.Debug.Log("Error while Receiving: " + www.error);
    }
    else
    {
        UnityEngine.Debug.Log("Success");

        //Load Image
        Texture2D texture2d = new Texture2D(8, 8);
        Sprite sprite = null;
        if (texture2d.LoadImage(handle.data))
        {
            sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), Vector2.zero);
        }
        if (sprite != null)
        {
            imageToUpdate.sprite = sprite;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用UnityWebRequestTexture.GetTextureDownloadHandlerTexture.GetContent功能来更快地下载、处理和获取图像。

IEnumerator downloadImage()
{
    string url = "http://wallpaper-gallery.net/images/hq-images-wallpapers/hq-images-wallpapers-12.jpg";

    UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);

    DownloadHandler handle = www.downloadHandler;

    //Send Request and wait
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        UnityEngine.Debug.Log("Error while Receiving: " + www.error);
    }
    else
    {
        UnityEngine.Debug.Log("Success");

        //Load Image
        Texture2D texture2d = DownloadHandlerTexture.GetContent(www);

        Sprite sprite = null;
        sprite = Sprite.Create(texture2d, new Rect(0, 0, texture2d.width, texture2d.height), Vector2.zero);

        if (sprite != null)
        {
            imageToUpdate.sprite = sprite;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)