如何从url下载文件并使用unity3d在C sharp中保存位置
本文关键字:unity3d sharp 位置 保存 url 下载 文件 | 更新日期: 2023-09-27 18:10:18
我在做unity3d项目。我需要一组文件从服务器下载。我使用c#编写脚本。在谷歌上搜索了一个小时后,我还没有找到解决方案,因为文档太差了。谁能给我的例子代码下载文件从url和保存在unity3d的特定位置?
Unity3D使用被称为Mono的c#实现。Mono几乎支持标准。net库中的所有可用功能。因此,当你想知道"我如何在Unity中做到这一点?",你可以在msdn.com上查看。net的文档,它一点也不差。关于你的问题,使用WebClient
类:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
WebClient client = new WebClient();
Stream data = client.OpenRead(@"http://google.com");
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
Console.WriteLine(s);
data.Close();
reader.Close();
}
}
编辑下载镜像文件时,使用WebClient
提供的DownloadFile
方法:
WebClient client = new WebClient();
client.DownloadFile("http://upload.wikimedia.org/wikipedia/commons/5/51/Google.png", @"C:'Images'GoogleLogo.png")
看看Unity 3d中的WWW功能。
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
IEnumerator Start() {
WWW www = new WWW(url);
yield return www;
renderer.material.mainTexture = www.texture;
}
}
资源包,如果你想压缩你的数据包。
var www = new WWW ("http://myserver/myBundle.unity3d");
yield www;
// Get the designated main asset and instantiate it.
Instantiate(www.assetBundle.mainAsset);
注意一些函数只有Ready only…比如www.url函数。一些示例也被移到了手册部分,而不是脚本部分。
希望对你有帮助。
标记
您可以使用System.Net.WebClient异步下载文件。
之类的 System.Net.WebClient client = new WebClient();
client.DownloadFileAsync(new Uri("your uri"), "save path.");
我找到了一个很好的例子,可以使用unity3d在这里
Unity的WWW
类&方法组已弃用。使用UnityWebRequest
是当前推荐的处理web请求的方法,特别是GET请求:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class MyBehaviour : MonoBehaviour {
void Start() {
StartCoroutine(GetText());
}
IEnumerator GetText() {
UnityWebRequest www = UnityWebRequest.Get("http://www.my-server.com");
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
// Show results as text
Debug.Log(www.downloadHandler.text);
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
}
}
}