在Unity3d中继续代码之前等待web调用完成
本文关键字:web 等待 调用 Unity3d 继续 代码 | 更新日期: 2023-09-27 18:15:27
我读了很多文章,但我似乎不明白。我现在有这个代码工作,因为我硬编码一个3秒的延迟,所以有足够的时间为网络调用完成,所以当分数显示有数据。但我真正想要的是有web调用完成,然后显示比分。帮助吗?
IEnumerator Start()
{
client = new MobileServiceClient(_appUrl, _appKey);
table = client.GetTable<Highscore>("Highscores");
yield return StartCoroutine(ReadItems());
DisplayScores();
}
void Update()
{
}
public void btn_GoBack()
{
Application.LoadLevel("StartScene");
}
private void OnReadItemsCompleted(IRestResponse<List<Highscore>> response)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Debug.Log("OnReadItemsCompleted data: " + response.Content);
List<Highscore> items = response.Data;
Debug.Log("Read items count: " + items.Count);
Scores = items;
}
else
{
Debug.Log("Error Status:" + response.StatusCode + " Uri: " + response.ResponseUri);
}
}
private IEnumerator ReadItems()
{
table.Read<Highscore>(OnReadItemsCompleted);
yield return new WaitForSeconds(3);
}
private void DisplayScores()
{
txtHighScores.text = "";
int numberOfScores = Math.Min(Scores.Count, 5);
for (int i = 0; i < numberOfScores; i++)
{
string name = Scores[i].username.ToString();
string score = Scores[i].score.ToString();
txtHighScores.text += (i + 1).ToString() + ". " +
" - " + name + "'r'n" +
score.ToString().PadLeft(4, '0');
}
}
通过Startcorutine方法传递参数是很重要的,否则会给出错误。所以尝试我的修复在你的代码。
IEnumerator Start()
{
client = new MobileServiceClient(_appUrl, _appKey);
table = client.GetTable<Highscore>("Highscores");
yield return StartCoroutine(ReadItems(2.0f)); //delay
DisplayScores();
}
IEnumerator ReadItems(float delay)
{
yield return new WaitForSeconds(delay);
table.Read<Highscore>(OnReadItemsCompleted);
}
- 从
Start()
中删除DisplayScores()
的方法调用 - 并插入
DisplayScores()
作为方法回调OnReadItemsCompleted
的最后一行然后删除
yield return new WaitForSeconds(3);
行