How to check whether the device is connected to internet or not in Unity

If you want to check is the Unity game running in a device connected to internet or not, you can call this coroutine function:

IEnumerator CheckInternetConnection() {
        using (UnityWebRequest webRequest = UnityWebRequest.Get("https://googleads.g.doubleclick.net/"))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();
            switch (webRequest.result)
            {
                case UnityWebRequest.Result.ConnectionError:
                    Debug.Log("No Internet");
                    break;
                case UnityWebRequest.Result.DataProcessingError:
                    Debug.Log("No Internet");
                    break;
                case UnityWebRequest.Result.ProtocolError:
                    Debug.Log("No Internet");
                    break;
                case UnityWebRequest.Result.Success:
                    Debug.Log("Connected to the Internet");
                    break;
            }
        }
    }

Simply call that coroutine function like this:

StartCoroutine(CheckInternetConnection());

Then wait for a message in your Unity console about internet connection.

Don’t forget to use Networking namespace:

using UnityEngine.Networking;

Leave a Reply

Your email address will not be published. Required fields are marked *