Question by
MobinYaqoob · Oct 17, 2016 at 02:40 PM ·
unity 5interfaceinternet
How to Check is Internet Available without creating overhead in Unity3d
I Need to check that if internet is avaiable or not in my games so that i make decission. There are two different types of decission when internet is working and when internet is not working. current i found a way but it create a overhead to cpu. Current i am using this type of solutions . is there a better way to check either internet is avaiable or not.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DeviceConnected : MonoBehaviour
{
private const bool allowCarrierDataNetwork = false;
private const string pingAddress = "8.8.8.8"; // Google Public DNS server
private const float waitingTime = 2.0f;
public Text txtInternetConnectStatus;
private Ping ping;
private float pingStartTime;
public void Start()
{
InvokeRepeating("OnStartCheck", 0f,3.0f);
}
public void OnStartCheck()
{
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)
{
Debug.Log("Hi");
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 :(");
txtInternetConnectStatus.text = "No Internet :(";
isInternetAvailable = true;
}
private void InternetAvailable()
{
Debug.Log("Internet is available! ;)");
txtInternetConnectStatus.text = "Internet is available! ;)";
isInternetAvailable = false;
}
}
Comment
I imagine there will always be some overhead to it. Here seems to be another simple solution: http://answers.unity3d.com/questions/534873/testing-for-active-internet-connection.html