首页 > 解决方案 > 如何在 C# 中等待 IEnumerator 函数的完整执行?

问题描述

我想在另一个函数中获取 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#unity3dcoroutineienumeratorunitywebrequest

解决方案


问题

线

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

推荐阅读