我想在另一个函数中得到一个webrequest的结果,但不幸的是,webrequest的变量一直是空的,因为当我调用这个变量时,webrequest还没有被执行。我调用了OpenFile函数,它调用了GetText函数。
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是空的.
有什么办法可以解决这个问题吗?
谢谢你!我想得到一个函数的结果,但在OpenFile函数中的m_fileContent是空的。
该行
Console.Log(m_fileContent);
是立即达成的,不需要等到Coroutine完成。
用一个 Action<string[]>
并传入一个回调,如e.g.
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);
}