计算从客户端到服务器请求数据所需的时间 - Unity

时间:2016-09-19 18:18:51

标签: c# unity3d client-server

所以标题说明了一切 - 然而我尝试的方法似乎不起作用,我不知道为什么。

 public static IEnumerator RetrieveCharacterData(string userid, Action<string> charSelectResponse)
 {
    WWWForm data = new WWWForm();
    data.AddField("userid", userid);

    // Send request to server
    WWW characterSelectRequest = new WWW(Helper.Constants.kCharacterSelectUrl, data);
    float elapsedTime = 0.0f;

    while (!characterSelectRequest.isDone)
    {
        elapsedTime += Time.deltaTime;

        Debug.Log(elapsedTime); // This prints in real time the correct data

        if (elapsedTime >= Helper.Constants.ConnectionTimeoutInterval)
        {
            Debug.Log("Server error: Connection has timed out.");
            yield return null;
        }
    }

    // This doesn't work - prints out garbage values
    Debug.Log(elapsedTime); 


    if (!characterSelectRequest.isDone || !string.IsNullOrEmpty(characterSelectRequest.error))
    {
        charSelectResponse.Invoke(null);
        yield break;
    }
    charSelectResponse.Invoke(characterSelectRequest.text);
}
  • 因此经过一些编辑后,这让我最接近我的想法 - 但是当我尝试获取实际的elapsed时,它会打印出垃圾值。

1 个答案:

答案 0 :(得分:2)

if (Time.time - startTime >= Helper.Constants.ConnectionTimeoutInterval)

>=应为<

目前,在请求完成之前,您已停留在该循环中而不会屈服。然后跳过下一个if块,最后在同一个调用上执行elapsedTime检查,而不会屈服,导致零时差,就Unity的时间而言。