簡體   English   中英

在foreach循環Unity3D C#中的協程

[英]Coroutine in foreach loop Unity3D C#

大家!

我正在嘗試使用foreach上傳多個文件。 到目前為止,我已成功上傳所有內容,但我想先完成協程,然后繼續進行for循環中的下一項bc我將要進行進度條。 由於某種原因,協同程序都是在一個而不是一個一個地執行。

這是我的代碼:

    public void CallUploadFile() //Called by button
    {
        StartCoroutine(UploadScene());
    }

    IEnumerator UploadScene()
    {
        foreach(string str in item_list)
        {
            string item_path = str;
            yield return new StartCoroutine(StartUpload (item_path));
        }
    }

    IEnumerator StartUpload(string item_path)
    {
         byte[] image_bytes;
         image_bytes = File.ReadAllBytes(item_path);

         // upload using WWWForm;
        WWWForm form = new WWWForm ();
        form.AddBinaryData ("scene[image]", image_bytes);
        using (UnityWebRequest www = UnityWebRequest.Post("somelink.com/upload", form))
        {
             yield return www.Send();
            while (!www.isDone)
            {
               Debug.Log(www.progress);
               yield return null
            }
            Debug.Log("Success!");
        }
    }

我已在各種論壇上閱讀過有關此主題的內容,此代碼應該可以正常工作,但由於某些原因,這種方法無法正 任何抬頭都會非常感激。

使用下面的代碼:這將使返回null之前的所有代碼完成,這符合您的需要。

IEnumerator UploadScene()
{
    foreach(string str in item_list)
    {
        string item_path = str;
        StartUpload (item_path));
    }
    yield return null;   //returns until work is done.
}

void StartUpload(string item_path)
{
     byte[] image_bytes;
     image_bytes = File.ReadAllBytes(item_path);

     // upload using WWWForm;
}

你的外部枚舉可以產生內部的枚舉

IEnumerator UploadScene()
{
    foreach(string str in item_list)
    {
        string item_path = str;
        yield return StartUpload (item_path);
    }
}

編輯:我無法在文檔中找到send方法, https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest.html

你確定它會返回收益指令嗎? 你可以跳過它,只使用yield return null而不是完成代碼

edit2:有一個異步SendWebRequest方法。 其返回值與Coroutines不兼容。

我認為你的代碼工作正常,但你打印錯了。

IEnumerator UploadScene()
{
    foreach(string str in item_list)
    {
        string item_path = str;
        yield return new StartCoroutine(StartUpload (item_path));
    }
}

一旦前一個協同程序結束,你正在准備好開始每個協同程序。 到目前為止,我會說這么好。

IEnumerator StartUpload(string item_path)
{
     // Code
    using (UnityWebRequest www = UnityWebRequest.Post("somelink.com/upload", form))
    {
         yield return www.Send();
        while (!www.isDone)
        {
           Debug.Log(www.progress);
           yield return null
        }
        Debug.Log("Success!");
    }
}

你正在放棄發送請求,這將在某種程度上“停止”協程,直到下載完全完成。 接下來,如果沒有完成,請打印,但直到下載結束為止。

所以我希望你只有成功的印刷。

你需要的是在循環中產生:

        www.Send();
        while (!www.isDone)
        {
           Debug.Log(www.progress);
           yield return null
        }

這將調用發送請求並將繼續。 但現在它將在while循環util中產生,因此它將逐個打印進度。

請記住,這會使您的下載時間更長。 您可以在同一個循環中觸發它們,然后Unity將啟動不同的線程(不是協同程序,正確的線程),因此您可以並行進行多次下載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM