using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
/// <summary>
/// 脚本挂在一个image上面
/// </summary>
public class NewBehaviourScript : MonoBehaviour
{
/// <summary>
/// 百度随便找的一张图
/// </summary>
string url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1608284553864&di=6fe752a8140c9c81d4aabbbf65b70bf0&imgtype=0&src=http%3A%2F%2Fa2.att.hudong.com%2F27%2F81%2F01200000194677136358818023076.jpg";
void Start()
{
StartCoroutine(getImage());
}
IEnumerator getImage()
{
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
// 网络错误
}
else
{
// 网络正常情况
// 先获取到图片的数据
byte[] results = unityWebRequest.downloadHandler.data;
// 创建一个 Texture,这个尺寸要自己定,我这里随便写的
Texture2D texture = new Texture2D(1920, 1080);
texture.LoadImage(results);
yield return new WaitForSeconds(0.01f);
// 使用 Texture 创建一个sprite
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
// 图片赋值
transform.GetComponent<Image>().sprite = sprite;
yield return new WaitForSeconds(0.01f);
Resources.UnloadUnusedAssets();
}
}
}
UnityWebRequest下载图片
最新推荐文章于 2024-04-10 22:12:12 发布