c# - foreach循环Unity3D C#中的协程

标签 c# unity3d upload ienumerator

大家好!

我正在尝试使用 foreach 上传多个文件。到目前为止,我已经成功上传了所有内容,但我想先完成协程,然后再继续进行 for 循环中的下一项,因为我要制作一个进度条。出于某种原因,协程全部被一起执行,而不是一个接一个地执行。

这是我的代码:

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

关于c# - foreach循环Unity3D C#中的协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49065300/

相关文章:

android - 使用Retrofit(Android)上传大视频文件出现OutOfMemoryError

csv - 我如何在 quicksight 中刷新 csv 数据集而不替换数据集,因为这会丢失我的计算

c# - 如何使用javascript捕获鼠标点击时sharepoint页面上的每个元素?

android - UnityPlayerActivity 没有收到 onCreate() 日志

c# - Unity动态加载和添加动画 Controller

unity3d - 如何旋转对象以沿向量指向 Unity3D

java - 我可以使用 PUT 和 HttpUrlConnection 将图像发送到我的共享主机帐户吗?

c# - 模拟 System.Web.Caching.Cache - 模拟或检查 null?

c# - Windows Azure 表访问花费的时间太长

c# - 使用 .NET 2.0 删除 List<T> 中的重复项