using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
public class NewBehaviourScript : MonoBehaviour
{
string downloadurl = @"https://lmg.jj20.com/up/allimg/1114/010421142927/210104142927-12-1200.jpg";
string savepath =null;
FileInfo file;
void Start()
{
savepath = Application.dataPath + "/666.jpg";
file = new FileInfo(savepath);
if (!file.Exists)
StartCoroutine(DownLoad());
else
Debug.LogError("已经存在");
}
IEnumerator DownLoad()
{
UnityWebRequest request = UnityWebRequest.Get(downloadurl);
yield return request.SendWebRequest();
if (request.isDone)
{
if (request.isHttpError || request.isNetworkError)
Debug.Log(request.error);
else
{
Debug.Log(request.downloadHandler.text);
byte[] bytes = request.downloadHandler.data;
CreatFile(bytes);
}
}
}
void CreatFile(byte[] bytes)
{
Stream stream;
stream = file.Create();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
stream.Dispose();
}
}
使用UnityWebRequest获取网络图片并保存
于 2022-11-18 14:32:55 首次发布
本文介绍了一个使用Unity进行网络图片下载并保存到本地的方法。通过UnityWebRequest组件发起GET请求,下载完成后将图片数据写入文件中。代码展示了如何处理下载过程中的错误,并提供了一个简单的检查机制来避免重复下载。
4167

被折叠的 条评论
为什么被折叠?



