Table of Contents
Checking Internet Connection in Unity
In Unity, ensuring your app can detect an active internet connection is crucial, especially for applications that rely on online data or functionalities. Here are some effective strategies:
Using UnityWebRequest
One of the most straightforward methods is using the UnityWebRequest
class to ping a reliable server. Here’s a code example:
Discover new games today!
using UnityEngine; using UnityEngine.Networking; using System.Collections; public class InternetChecker : MonoBehaviour { void Start() { StartCoroutine(CheckInternetConnection((isConnected) => { Debug.Log("Internet connected: " + isConnected); })); } IEnumerator CheckInternetConnection(System.Action<bool> callback) { UnityWebRequest request = new UnityWebRequest("http://www.google.com"); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.ConnectionError && request.result != UnityWebRequest.Result.ProtocolError) { callback(true); } else { callback(false); } } }
Advantages of UnityWebRequest
- Easy to implement and understand.
- Allows you to check specific server availability.
Using DNS Resolution
Another method involves checking for DNS resolution using System.Net.NetworkInformation
:
using System.Net.NetworkInformation; public static bool IsInternetAvailable() { try { return NetworkInterface.GetIsNetworkAvailable(); } catch (Exception ex) { Debug.LogWarning("Network check failed: " + ex.Message); return false; } }
Benefits of DNS Resolution
- Low overhead, no need to hit external servers.
- Checks basic network connectivity.
Both methods have their pros and cons. Using UnityWebRequest
is more effective if you need to ensure a specific service is reachable. On the other hand, DNS Resolution is faster and less resource-intensive if merely checking network connectivity suffices.