我一直在尝试让一些 API 通信正常工作。我正在使用 UnityWebRequests,因为我想构建为 WebGL(我尝试了 System.Net.WebRequest,它在游戏模式下工作,但与 WebGL 不兼容)。这可能只是协程的问题,但我将以半伪的形式向您展示我到目前为止所拥有的以及我的问题是什么:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
public class scking : MonoBehaviour
{
string tempText;
string getUri = "https://api.opensensors.com/getProjectMessages";
string jwtToken = "someToken";
private void Start()
{
pullAllData();
}
IEnumerator GetDataRequest(string currentDateString, string nextDateString, string sensorID)
{
string requestParam = "myparameters: " + nextDateString + sensorID; // simplified dummy parameters
using (UnityWebRequest webRequest = UnityWebRequest.Get(requestParam))
{
webRequest.SetRequestHeader("Authorization", "Bearer " + jwtToken);
webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();
// from unity api example
string[] pages = getUri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
// getting the data i pulled out of the coroutine for further manipulation
this.tempText = webRequest.downloadHandler.text;
// show whats been pulled
print(this.tempText);
}
}
void pullAllData()
{
int allDaysCount = 10;
List<int> sensorIds; // initialized with some ids
for(int i = 0; i < allDaysCount - 1; i++)
{
for(int j = 0; j < sensorIds.Count; j++)
{
StartCoroutine(GetDataRequest(i, i + 1, sensorIds[j]));
// show whats been pulled
print(this.tempText);
// parse json string this.tempText etc.
}
}
}
}
输出为(按时间排序)
来自 pullAddData:null 中的打印
然后从协程中的 print 中下一步: jsonItem
基本上,协程花费的时间太长而且太晚了,我的循环无法继续,而且因为我得到一个空值,我当然无法解析或操作我的数据。或者也许我的整个工作都有缺陷,在这种情况下,如何正确地做到这一点?
非常感谢您对此提供的任何帮助。善良的菲利普