unity 使用HttpBest加载图片
时间: 2023-12-16 15:04:31 浏览: 46
Unity 中可以使用 HttpWebRequest 或 HttpClient 等方式来进行 Http 请求并加载图片。以下是一个使用 HttpWebRequest 的例子:
```c#
using UnityEngine;
using System.IO;
using System.Net;
public class HttpImageLoader : MonoBehaviour
{
public string url;
void Start()
{
StartCoroutine(LoadImage());
}
IEnumerator LoadImage()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowWriteStreamBuffering = true;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
Texture2D texture = new Texture2D(0, 0);
texture.LoadImage(ReadFully(stream));
GetComponent<Renderer>().material.mainTexture = texture;
}
}
yield return null;
}
byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
```
这个例子会使用 HttpWebRequest 请求指定的图片 URL,然后将其加载到一个 Texture2D 对象中,并将其设置为当前对象的渲染材质的主纹理。在 Start 函数中调用 LoadImage 函数,使用 StartCoroutine 来启动协程,以异步的方式进行图片加载。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![unitypackage](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)