【发布时间】:2020-12-22 04:07:51
【问题描述】:
我正在使用 Unity 和 C# 构建一个游戏,当玩家将鼠标悬停在项目上时,会调用 UnityWebRequest 来处理 SPARQL 查询。我想为查询输出的 JSON 响应返回一个字符串。我无法从协程中获取返回值。到目前为止,我已经尝试过使用“回调”,尽管我不完全确定它是如何工作的。在协程从 webrequest 中检索数据后,我想操纵 JSOn 响应。有谁知道如何让它工作或有任何提示?谢谢!!
调用协程的脚本
internal class HighlightSelectionResponse : MonoBehaviour, ISelectionResponse
{
public TextMeshProUGUI gameText;
public RESTGet rest;
private static string itemName;
private string URL;
string returnData;
public void OnSelect(Transform selection)
{
// this method only works if a query toggle is checked
if (rest.queryUsage == true)
{
var itemName = selection.name.ToString(); // name of the gameobject
var URL = rest.queryURL + itemName;
Debug.Log(URL);
// START COROUTINE
StartCoroutine(rest.GetData2(URL, (value)=> { returnData = value; } ));
Debug.Log(returnData); <=== returns Null
}
}
使用协程编写脚本
public IEnumerator GetData2(string uri, System.Action<string> callback)
{
UnityWebRequest webRequest = UnityWebRequest.Get(uri);
// Call/Request website and wait to finish
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError || webRequest.isHttpError)
{
Debug.Log("No response from website");
}
else
{
//process web result
Debug.Log("Data retrieved!");
callback(webRequest.downloadHandler.text);
}
}
【问题讨论】: