C# 从url加载和显示图像

C# 从url加载和显示图像,c#,image,url,unity3d,C#,Image,Url,Unity3d,我正在尝试将图像从url加载到GameObject 我找到了下一个教程: 下载成功,但我看不到图像 我做错了什么 // 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.

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

我找到了下一个教程:

下载成功,但我看不到图像

我做错了什么

// 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
    }
}
//将其用于初始化
无效开始(){
Start例程(loadSpriteImageFromUrl(“https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/408px-Google_2015_logo.svg.png"));
}
IEnumerator loadSpriteImageFromUrl(字符串URL)
{
//检查互联网连接
if(Application.internetReachability==NetworkReachability.NotReachable)
{
收益返回空;
}
var www=新的www(URL);
Log(“下载进程中的图像”);
收益率;
if(string.IsNullOrEmpty(www.text))
{
Debug.Log(“下载失败”);
}
其他的
{
Debug.Log(“下载成功”);
纹理2d纹理=新纹理2d(1,1);
www.LoadImageIntoTexture(纹理);
雪碧雪碧=雪碧。创建(纹理,
新的矩形(0,0,纹理.宽度,纹理.高度),
向量2.1/2);
GetComponent().sprite=sprite;//更改当前sprite
}
}

编辑

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

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;    
    }
}
IEnumerator loadSpriteImageFromUrl(字符串URL,游戏对象单元格)
{
//检查互联网连接
if(Application.internetReachability==NetworkReachability.NotReachable)
{
收益返回空;
}
var www=新的www(URL);
Log(“下载进程中的图像”);
收益率;
if(string.IsNullOrEmpty(www.text))
{
Debug.Log(“下载失败”);
}
其他的
{
Debug.Log(“下载成功”);
纹理2d纹理=新纹理2d(1,1);
www.LoadImageIntoTexture(纹理);
雪碧雪碧=雪碧。创建(纹理,
新矩形(0,0,纹理.宽度,纹理.高度),
矢量2.1/2);
cell.AddComponent();
cell.GetComponent().sprite=sprite;
}
}
但我会在屏幕上看到下一个结果(而不是url中的图像):


您的代码很好。下载的图像未显示,因为您位于场景视图中,而相机远离场景视图

选择脚本所连接的游戏对象,然后按F。它应该放大,你会看到下载的图像。有关如何重置Unity布局以恢复游戏视图的信息,请参阅



如果您仍然看不到图像,则
SpriteRenderer
不在相机前面。从屏幕截图上看,它的位置是
0
0
0
,因此确保相机的位置是
0
0
-10

显示图像的正确方式:

要简单地统一显示图像,请使用
image
RawImage
组件<由于更改纹理时不会生成垃圾,因此建议使用“代码>原始图像”。您应该已经知道如何从

如果需要将刚体或二维碰撞器附加到该图像,则对三维对象使用
SpriteRenderer
MeshRenderer
,以显示
图像

这是四种统一显示图像的方法#2如果根本不需要物理或碰撞,建议使用:

1。使用
图像
组件:

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;
    }
}
过去,
LoadImageIntoTexture
存在问题。因此,我的其他示例将不使用
LoadImageIntoTexture
。如果在图像中看到问号,请使用
www.bytes
Texture2D.LoadImage
功能

只需替换:

Texture2D texture = new Texture2D(1, 1);
www.LoadImageIntoTexture(texture);


2。使用
rawmimage
组件(推荐的):

3。使用
Spirterender
组件:

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;
    }
}
主要用于使用刚体2D和2D碰撞器进行2D对象和2D物理模拟。如果没有,则使用上面的UI(#1#2

4。使用
MeshRenderer
组件:

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;
    }
}
主要用于刚体和2D碰撞器的3D对象和3D物理模拟。如果没有,则使用上面的UI(#1#2)。只需使用带有
网格渲染器的平面、四边形或立方体即可

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

新统一版本:

WWW
API现在似乎被弃用了<现在应使用代码>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;
        }
    }
}
您还可以使用
UnityWebRequestTexture.GetTexture
DownloadHandlerTexture.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;
        }
    }
}

上面的脚本附加在您的
层次结构中的哪里
?资产-->脚本-->加载映像。它连接到一个空的游戏对象上。为什么?你的空
GameObject
需要有一个
spriteender
组件,否则你的脚本将永远无法运行work@Hristo我已经有喷灯了。@程序员我已经有喷灯了。我想显示一个网格的图像从网上。再次感谢您的详细回答。我尝试了#1和#2,但不幸的是,我仍然得到了一个带有红色的白色正方形
标记你的Unity版本是什么?你能给我一个简单的项目,没有工作吗?我来看看。顺便问一下,你原来的喷灯问题解决了吗?我只是想知道…5.6.0f3。我能把它寄过来吗?在#2解决方案中,我不需要SpriteRender,我只使用了一个没有它的RawImage对象。现在来看看。从我的电脑里得知代码工作正常。我不知道你是不是在骗我。如果你愿意,你就不会有这个问题
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;
        }
    }
}