分享

c# – 使用WebClient在Unity3d中下载大文件

 印度阿三17 2019-05-28

我正在寻找有关使用WebClient在Unity3d中下载大(100mg)文件的任何想法. WWW以异步方式运行并且完美无缺,除非它返回内存错误并导致应用程序崩溃,因此我已按照此处所述移至解决方案:

how to download a file from url and save in location using unity3d in C sharp?

这就像一个梦想,除了它关闭我的应用程序中的所有脚本,直到下载完成.我似乎无法在下载进行的同时运行加载栏.我已经尝试通过添加协程来处理下载,但到目前为止,没有运气.

任何帮助,将不胜感激.我的代码目前(经过多次迭代)看起来像:

C#

 void Update()
    {
    //Sets up the timer so I can use it to watch the debugging
        timer  = Time.deltaTime;
        Debug.Log (timer);

//Checks to see if the file was already downloaded and saved.  If not, it begins downloading.
    if (FileExists == 0 && timer >= 5) {
        StartCoroutine ("DOWNLOAD");

    } 
//If the file already exists, it jumps straight to the next scene.
    else if (FileExists == 1) {
        Application.LoadLevelAsync ("Different_Level");
    }

    //These are the buttons.  One should stop the download if the player decides they don't want to wait.
    if (Input.GetMouseButtonUp (0)) {

        RaycastHit rc_hit;
        Ray hud_ray = Camera.main.ScreenPointToRay (Input.mousePosition);

    if (Physics.Raycast (hud_ray, out rc_hit, Mathf.Infinity, 1 << LayerMask.NameToLayer ("HUD"))) {

    if (rc_hit.transform.gameObject == b_BackButton) {

        StopCoroutine ("EN_Loop");
        Application.LoadLevelAsync ("Other_Level"); 
                            }
                    }
            }

}

//This is what should happen when the video is done downloading
void AllDone ()

{
    Debug.Log ("Download Complete");
    Application.LoadLevelAsync ("Next_Level");
}

////This is the coroutine I created int he hopes that I could get the download to run in the background.
IEnumerator DOWNLOAD()
{
    Debug.Log("downloading_EN");
    WebClient client = new WebClient();
    client.DownloadFile ("http://ServerInfo.net/moviefile.mp4", Application.persistentDataPath   "/"   "moviefile.mp4");
    yield return null;

    AllDone ();

}

解决方法:

尝试使用WebClient.DownloadFileAsync来锁定主线程(这样您的其他脚本仍将运行)并使用WebClient.DownloadFileCompleted事件来了解它何时完成.

无需使用Coroutine来使用WebClient,并确保只调用此方法一次:

void DownloadFile()
{
    WebClient client = new WebClient();
    client.DownloadFileCompleted  = new System.ComponentModel.AsyncCompletedEventHandler( DownloadFileCompleted );
    client.DownloadFileAsync ((new Uri ("http://ServerInfo.net/moviefile.mp4", Application.persistentDataPath   "/"   "moviefile.mp4"));
}

void DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    if (e.Error == null)
    {
        AllDone ();
    }
}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多