gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:51 26 4
gpt4 key购买 nike

大家好!

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com