问题
How can I check internet connection inside Update Function in unity? I want to know whether the user is connected or not, and based on that just disable some functionality of my game.
Seems like there is no question like this been asked here before or if it is, it just checking the connection in Start function. Here is the code I have so far:
void Update () {
if (Application.internetReachability == NetworkReachability.NotReachable) {
Debug.Log ("No internet access");
} else {
Debug.Log ("internet connection");
}
}
回答1:
You need to run your Update
function periodically.
http://unitylore.com/articles/timers-in-unity/ could be used for this:
using UnityEngine;
public class Timer : MonoBehaviour
{
public float waitTime = 1f;
float timer;
void Update ()
{
timer += Time.deltaTime;
if (timer > waitTime) {
if (Application.internetReachability == NetworkReachability.NotReachable) {
Debug.Log ("No internet access");
} else {
Debug.Log ("internet connection");
}
timer = 0f;
}
}
}
回答2:
@mjwills solution is right and it works OK, but nobody forces you to check connection every single frame of your game. You don't have to do that.
A better solution is to check connection when a button is clicked or when an event happens in your scene.
回答3:
Unity's Application.internetReachability is not the best solution for internet detection as it was not designed for that purpose (as stated in the docs).
The proper way is to implement a technique called Captive Portal Detection, which is what all the major OS's use for their internet status detection. If implemented correctly, it can even detect when the network is restricted (hotels or airports) as it relies on HTTP requests of known content. Therefore it is far more reliable.
It is not that hard to implement. You need to make an HTTP request to a known "check page", and check whether the right content were returned.
However, if you want a complete, ready-to-use solution, you can check the asset Eazy NetChecker which I created for this purpose. It also has events and a custom editor. It is not free, but it is super cheap!
来源:https://stackoverflow.com/questions/45647331/checking-internet-connection-at-runtime-in-unity