简体   繁体   English

在继续进行Unity3d中的代码之前,等待网络调用完成

[英]Waiting for web call to finish before continuing code in Unity3d

I've read many articles but I don't seem to get it. 我读了很多文章,但我似乎不明白。 I have this code working now because I hardcode a 3 second delay so there is enough time for the web call to finish so when the score is displayed there is data. 我现在可以使用此代码,因为我对3秒的延迟进行了硬编码,因此有足够的时间完成网络通话,因此在显示分数时就有数据。 But what I really want is to have the web call finish and THEN display the score. 但是我真正想要的是让网络通话结束,然后显示分数。 Help ? 救命 ?

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

It is important to pass a parameter with Startcorutine method, Otherwise it gives error. 使用Startcorutine方法传递参数很重要,否则会出错。 So try my fix in your code. 因此,请尝试在您的代码中进行修复。

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

}
  1. Remove the method call for " DisplayScores() " from Start() Start()删除对“ DisplayScores() ”的方法调用
  2. And insert DisplayScores() as the last line of method callback OnReadItemsCompleted 并将DisplayScores()插入为方法回调OnReadItemsCompleted的最后一行
  3. And then you should remove the line yield return new WaitForSeconds(3); 然后应该删除行yield return new WaitForSeconds(3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM