I am porting our game to Unity, and need some help regarding internet connectivity check in Unity. Official Unity Documentation says 'do not use Application.internetReachability. So i am confused which code will work here. Didn't find any prominent solution in any forum. I want to check whether wi-fi or GPRS is on or not which should work for iOS and Android. Thanks in advance.
Application.internetReachability is what you need. In conjunction with Ping, probably.
Here's an example:
using UnityEngine;
public class InternetChecker : MonoBehaviour
{
private const bool allowCarrierDataNetwork = false;
private const string pingAddress = "8.8.8.8"; // Google Public DNS server
private const float waitingTime = 2.0f;
private Ping ping;
private float pingStartTime;
public void Start()
{
bool internetPossiblyAvailable;
switch (Application.internetReachability)
{
case NetworkReachability.ReachableViaLocalAreaNetwork:
internetPossiblyAvailable = true;
break;
case NetworkReachability.ReachableViaCarrierDataNetwork:
internetPossiblyAvailable = allowCarrierDataNetwork;
break;
default:
internetPossiblyAvailable = false;
break;
}
if (!internetPossiblyAvailable)
{
InternetIsNotAvailable();
return;
}
ping = new Ping(pingAddress);
pingStartTime = Time.time;
}
public void Update()
{
if (ping != null)
{
bool stopCheck = true;
if (ping.isDone)
{
if (ping.time >= 0)
InternetAvailable();
else
InternetIsNotAvailable();
}
else if (Time.time - pingStartTime < waitingTime)
stopCheck = false;
else
InternetIsNotAvailable();
if (stopCheck)
ping = null;
}
}
private void InternetIsNotAvailable()
{
Debug.Log("No Internet :(");
}
private void InternetAvailable()
{
Debug.Log("Internet is available! ;)");
}
}