Search Unity

Question Testing if internet access is available

Discussion in 'Scripting' started by pKallv, Jun 23, 2022.

  1. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    I am currently testing this code for this:

    Code (CSharp):
    1. IEnumerator CheckInternetConnection()
    2.     {
    3.         UnityWebRequest request = new UnityWebRequest("http://google.com");
    4.         yield return request.SendWebRequest();
    5.         if (request.error != null)
    6.         {
    7.             Debug.Log("*** NO INTERNET ***");
    8.             isInternetActive = false;
    9.         }
    10.         else
    11.         {
    12.             Debug.Log("*** INTERNET AVAILABLE ***");
    13.             isInternetActive = true;
    14.         }
    15.     }
    However, it takes quite a long time (10+ seconds), in the editor, to finish. I guess if players must wait this amount of time to play I have a problem.

    How do you handle this question and what is the best and fastest way of checking this?
     
  2. I don't do this (I never needed if internet is enabled or not for the games I worked on), but in your case they invented timeout for this. You trade accuracy (slow internet connection can be detected as offline) for speed. As usual.
     
    pKallv likes this.
  3. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Thanks.
     
  4. MaskedMouse

    MaskedMouse

    Joined:
    Jul 8, 2014
    Posts:
    1,092
    The downside about timeout is, that when you download large files and the timeout has been reached it will cancel the ongoing download. Even though you have a full speed connection going. Once the timeout is reached it will automatically throw. It does not reset in any way, once the download starts, it starts counting. No matter whether you have a good or bad connection.
    You'd have to monitor the amount of bytes that are downloaded.

    UnityWebRequest
    does not separate errors, nor does it throw any usable exceptions.
    All you know is that the request failed. Not what happened with it unless you specifically read out values like the response code and the error string.

    I've already suggested features for UnityWebRequest on the Roadmap. It would sure make handling failing / slow requests a lot easier. As well for UI.
     
  5. For this use case, none of these matter. Pinging if there is internet connection involves downloading the smallest content possible. So theoretically resume or fails don't matter. Or even result content.
     
    pKallv likes this.
  6. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Correct I just want to ping internet in the shortest time possible to setup my game correctly for single- vs. multiplayer.
     
  7. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,191
    Hmmm every time I test without internet editor hangs.