Unity 检查互联网连接可用性 [英] Unity check internet connection availability

查看:46
本文介绍了Unity 检查互联网连接可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将我们的游戏移植到 Unity,在 Unity 中需要一些有关互联网连接检查的帮助.官方 Unity 文档说不要使用 Application.internetReachability".所以我很困惑哪些代码可以在这里工作.在任何论坛中都没有找到任何突出的解决方案.我想检查 wi-fi 或 GPRS 是否打开,这应该适用于 iOS 和 Android.提前致谢.

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 正是您所需要的.可能与 Ping 结合使用.

Solution

Application.internetReachability is what you need. In conjunction with Ping, probably.

这是一个例子:

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! ;)");
    }
}

注意事项

  1. Unity 的 ping 不做任何域名解析,即它只接受 IP 地址.因此,如果某个玩家可以访问 Internet 但遇到一些 DNS 问题,则该方法会说他有 Internet.
  2. 这只是一个 ping 检查.不要期望它是 100% 准确的.在极少数情况下,它会向您提供虚假信息.

这篇关于Unity 检查互联网连接可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆