Unity加载网络图片并显示在UGUI上,解决加载网络图片出现问号的问题及其案例分析,实例Demo亲测可用

版权声明:转载请注明出处。 https://blog.csdn.net/QWBin/article/details/82464387

Unity加载网络图片并显示在UGUI上,解决加载网络图片出现问号的问题及其案例分析,实例Demo亲测可用

最近自己在加载网络图片的时候也遇到了加载的图片无法显示或者是问号的问题。下面就分析下为什么会出现这样的情况。

首先我们直接上代码(比较简单)

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ButtonHTTP : MonoBehaviour
{
    // 图片的地址 
    string url = "https://img04.sogoucdn.com/app/a/100520076/a5ec7bf55c2e54146b92abf35e1b7503";
    Image Myimage; // 初始化Image图片
    IEnumerator Start() // 协程
    {
        WWW www = new WWW(url);//用WWW加载网络图片
        yield return www;
        Myimage = transform.GetComponent<Image>();
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            //获取Texture
            Texture2D texture = www.texture;
            //因为我们定义的是Image,所以这里需要把Texture2D转化为Sprite
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            Myimage.sprite = sprite;
        }
    }
}

Unity界面:调整一下Button的大小,用来显示图片。

然后就是点击是直接可以显示网上的图片的。

但是有很多人在网上找到的图片加载后都是红色的“?”这是因为,加载的图片不是单个图片的连接,而是一堆图片。

那怎么解决这个问题尼?

首先在浏览器中随便找个图片,如下图:

然后任意图片位置,右键选择最下面的“检查”,点击后如下图:

然后双击图片,复制图片连接就可以用了,这样也不会有问号的问题了。

加载效果图:

Demo的话是unity资源包直接导入Unity就可以使用。

链接:https://pan.baidu.com/s/1yiUWabDvWA7InSpwNnHH0g 密码:6lya

猜你喜欢

转载自blog.csdn.net/QWBin/article/details/82464387