【问题标题】:How to wait for the complete execution of a IEnumerator function in C#?如何在 C# 中等待 IEnumerator 函数的完整执行?
【发布时间】:2020-08-24 00:45:04
【问题描述】:

我想在另一个函数中获取 webrequest 的结果,但不幸的是 webrequest 的变量保持为空,因为当我调用变量时 webrequest 尚未执行。我调用调用 GetText 的 OpenFile 函数:

private string[] m_fileContent;

public void OpenFile(string filePath)
    {
        StartCoroutine(GetText());
        Console.Log(m_fileContent);// is empty
    }

IEnumerator GetText()
    {
        UnityWebRequest www = UnityWebRequest.Get("http://...");
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            m_fileContent = www.downloadHandler.text.Split('\n');
            Debug.Log("here" + m_fileContent);//data printed ok

        }
    }

因此 GetText 函数打印文本,但在 OpenFile 函数中变量 m_fileContent 为空。

有什么办法解决这个问题吗?

谢谢!

【问题讨论】:

    标签: c# unity3d coroutine ienumerator unitywebrequest


    【解决方案1】:

    问题

    线

    Console.Log(m_fileContent);
    

    立即到达,不会等到协程完成。

    解决方案

    使用Action<string[]> 并传入回调,例如

    public void OpenFile(string filePath, Action<string[]> onTextResult)
    {
        // pass in a callback that handles the result string
        StartCoroutine(GetText(onTextResult));
    }
    
    IEnumerator GetText(Action<string[]> onResult)
    {
        UnityWebRequest www = UnityWebRequest.Get("http://...");
        yield return www.SendWebRequest();
    
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            var fileContent = www.downloadHandler.text.Split('\n');
    
            // Invoke the passed action and pass in the file content 
            onResult?.Invoke(fileContent);
        }
    }
    

    然后这样称呼它

    // Either as lambda expression
    OpenFile("some/file/path", fileContent => {
        Console.Log(fileContent);
    });
    
    // or using a method
    OpenFile("some/file/path", OnFileResult);
    
    ...
    
    private void OnFileResult(string[] fileContent)
    {
        Console.Log(fileContent);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多