如何从网址下载文件并使用C sharp中的unity3d保存在位置?

时间:2014-06-26 10:25:14

标签: c# unity3d

我正致力于unity3d项目。我需要从服务器下载一组文件。我使用C#编写脚本。经过一个小时的谷歌我没有找到解决方案,因为文档很差。任何人都可以从url给我下载文件的示例代码并将其保存在unity3d中的特定位置吗?

4 个答案:

答案 0 :(得分:6)

Unity3D使用称为Mono的C#实现。 Mono支持标准.NET库中提供的almost everything。因此,无论何时您想知道“我如何在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();
    }
}

修改 下载图像文件时,请使用DownloadFile提供的WebClient方法:

 WebClient client = new WebClient();
 client.DownloadFile("http://upload.wikimedia.org/wikipedia/commons/5/51/Google.png", @"C:\Images\GoogleLogo.png")

答案 1 :(得分:0)

看一下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);

请注意,某些功能仅仅是就绪...就像www.url功能一样。一些示例已移至“手动”部分,而不是脚本部分。

希望这有帮助。

-Mark

答案 2 :(得分:0)

您可以使用System.Net.WebClient异步下载文件。

类似

INSERT INTO MyTable(IdTable1, IDTable2)
SELECT t1.IDTable1, t2.IDTable2
FROM table1 t1
CROSS JOIN table2 t2

我找到了一个很好的示例,可以与unity3d here.

一起使用

答案 3 :(得分:0)

Unity的WWW类和方法组已被弃用。目前推荐使用UnityWebRequest处理Web请求,尤其是GET requests

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;
        }
    }
}