如何在没有fps下降的情况下统一检查互联网连接

时间:2018-09-24 10:51:14

标签: unity3d websocket connection frame-rate

我正在Unity上从事VR项目。在这个项目中,我们有websockets。对于某些Internet问题,我们要检查websocket是否仍然有效或出现错误,如果是这种情况,我们要检查Internet连接。如果互联网再次恢复正常运行,则需要重新连接到Websocket或将其重新初始化。现在,我们在更新功能中使用计时器来执行此操作,该计时器每秒触发一次,但每秒都有fps下降以检查互联网。还有其他解决方法吗?

public float waitTime = 1f;
private float timer;

private void Update()
{
    timer += Time.deltaTime;
    if (timer > waitTime)
    {
        //check if websocket is alive or that it must re initialized
        if (webSocket != null) //check if websocket was allready initialized 
        {
            if (isSocketError && Application.internetReachability != NetworkReachability.NotReachable) // check if an error was given by the websocket and ethernet is available again
            {
                CreateWebsocketSession(sessionId);
            }
            else if ((!webSocket.IsAlive || !webSocket.IsConnected) && Application.internetReachability != NetworkReachability.NotReachable) // check if websocket is alive and internet is available.
            {
                CreateWebsocketSession(sessionId);
            }
        }


        timer = 0f;
    }
}

1 个答案:

答案 0 :(得分:1)

  

调用函数时,该函数将运行到返回之前的完成状态。这个   有效地意味着在功能中发生的任何动作都必须   在一次更新中发生

我通常检查ping Google的互联网连接(Application.internetReachability不是确定实际连接性的好方法:docs

IEnumerator checkInternetConnection(Action<bool> action){
     WWW www = new WWW("http://google.com");
     yield return www;//wait for execution of this row, executed at Time x
     if (www.error != null) {//executed at time x+y, where y is the execution time(i think where you have drops)
         action (false);
     } else {
         action (true);//got internet here
     }
 } 

在您的情况下,请使用带有收益的Coroutine()而不是Update()