Unity下载资源且保存

 UnityWebRequest(WWW——已过时)

 替代:Unity不再支持WWW后,使用UnityWebRequest完成web请求。

Unity - Scripting API: UnityWebRequest (unity3d.com)icon-default.png?t=N7T8https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html

if (www.isNetworkError || www.isHttpError——已过时

替代:if(www.result == UnityWebRequest.Result.ConnectionError)

请求本地权限问题(疑是文件权限问题,未解决):

UnauthorizedAccessException:

Access to the path 'E:\Unity\Proj\xxx\xxx\h\to\file' is denied.

代码如下:
public class VideoDownloader : MonoBehaviour
{
    public string json;
    void Start()
    {
        // 协程
        // public Coroutine StartCoroutine(IEnumerator routine);
        StartCoroutine(DownloadVideo());
    }

    IEnumerator DownloadVideo()
    {
        // 使用UnityWebRequest
        UnityWebRequest www = UnityWebRequest.Get("http://localhost:9090/Video/unity_xmScene.mp4");
        yield return www.SendWebRequest();


        //if (www.isNetworkError || www.isHttpError)       // 已过时——2023年测
        Debug.Log(UnityWebRequest.Result.ConnectionError); // 返回值——ConnectionError
        if (www.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.Log(www.error);
        }
        else
        {
            Debug.Log("保存资源到本地!");

            // Show results as text
            Debug.Log(www.downloadHandler.text);

            // Or retrieve results as binary data
            byte[] results = www.downloadHandler.data;
            Debug.Log(results);

            //SaveJsonData("test2.txt");
            // 写字节——public static void WriteAllBytes(string path, byte[] bytes);
            // File.WriteAllBytes("path/to/file/", www.downloadHandler.data);
            File.WriteAllBytes("path/to/file/test.txt", www.downloadHandler.data);
        }

        /*// 使用过时WWW,WWW.bytes保存资源文件
        var www = new WWW("http://localhost:9090/Video/unity_xmScene.mp4");
        File.WriteAllBytes("path/to/file", www.bytes);*/
    }

亲测可行!

你可能感兴趣的:(Unity,unity)