如何使用 Unity 从 URL 加载图像?

How to load an image from URL with Unity?

请别让我发疯

无论我 google 多少次,我总是得到以下代码的(通常已弃用的)版本:

IEnumerator setImage(string url) {
    Texture2D texture = profileImage.canvasRenderer.GetMaterial().mainTexture as Texture2D;

    WWW www = new WWW(url);
    yield return www;

    Debug.Log("Why on earh is this never called?");

    www.LoadImageIntoTexture(texture);
    www.Dispose();
    www = null;
}

我使用的是 Unity 5 而不是 4。我正在尝试加载的 URL 存在。 请照亮我。

如何通过 HTTP 加载图像并将其显示在 UnityEngine.UI.Image 中?

多亏了Umair M的提问,才知道这个方法需要用unity的StartCoroutine.

来调用

快速说明: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html

public void yourMethod()
{
   StartCoroutine(setImage("http://url/image.jpg")); //balanced parens CAS
}

IEnumerator setImage(string url) {
    Texture2D texture = profileImage.canvasRenderer.GetMaterial().mainTexture as Texture2D;

    WWW www = new WWW(url);
    yield return www;

    // calling this function with StartCoroutine solves the problem
    Debug.Log("Why on earh is this never called?");

    www.LoadImageIntoTexture(texture);
    www.Dispose();
    www = null;
}

对于 Unity 2018+,使用 UnityWebRequest 替换 WWW class。

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

IEnumerator DownloadImage(string MediaUrl)
{   
    UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
    yield return request.SendWebRequest();
    if(request.isNetworkError || request.isHttpError) 
        Debug.Log(request.error);
    else
        YourRawImage.texture = ((DownloadHandlerTexture) request.downloadHandler).texture;
} 

你可以用 async/await:

using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

public static async Task<Texture2D> GetRemoteTexture ( string url )
{
    using( UnityWebRequest www = UnityWebRequestTexture.GetTexture(url) )
    {
        // begin request:
        var asyncOp = www.SendWebRequest();

        // await until it's done: 
        while( asyncOp.isDone==false )
            await Task.Delay( 1000/30 );//30 hertz
        
        // read results:
        if( www.isNetworkError || www.isHttpError )
        // if( www.result!=UnityWebRequest.Result.Success )// for Unity >= 2020.1
        {
            // log error:
            #if DEBUG
            Debug.Log( $"{www.error}, URL:{www.url}" );
            #endif
            
            // nothing to return on error:
            return null;
        }
        else
        {
            // return valid results:
            return DownloadHandlerTexture.GetContent(www);
        }
    }
}

用法示例:

[SerializeField] string _imageUrl;
[SerializeField] Material _material;
Texture2D _texture;

async void Start ()
{
    _texture = await GetRemoteTexture(_imageUrl);
    _material.mainTexture = _texture;
}

void OnDestroy () => Dispose();
public void Dispose () => Object.Destroy(_texture);// memory released, leak otherwise
public void OnStart()
{
    StartCoroutine(setImage("http://drive.google.com/myimage.jpg")); 
}

IEnumerator setImage(string url) 
{
    Texture2D texture = null;
    WWW www = new WWW(url);
    yield return www;

    Debug.Log("Why on earh is this never called?");
    texture = WWW.texture;
    //end show Image in texture 2D
}

我们不能直接在 canvas 中的图像组件上应用纹理 material。因此,我们应该从运行时下载的纹理创建一个精灵,然后将该精灵应用到图像组件中。

试试这个,

IEnumerator DownloadImage(string MediaUrl)
    {   
        UnityWebRequest request = UnityWebRequestTexture.GetTexture(MediaUrl);
        yield return request.SendWebRequest();
        if(request.isNetworkError || request.isHttpError) 
            Debug.Log(request.error);
        else{
            // ImageComponent.texture = ((DownloadHandlerTexture) request.downloadHandler).texture;

            Texture2D tex = ((DownloadHandlerTexture) request.downloadHandler).texture;
            Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
            ImageComponent.GetComponent<Image>().overrideSprite = sprite;
        }
    }