检查Unity的互联网连接 [英] Check for internet connectivity from Unity

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

问题描述

我有一个Unity项目,我为Android和iOS平台构建。我想检查桌面,Android和iOS设备上的互联网连接。我已经阅读了三种不同的解决方案:

I have a Unity project which I build for Android and iOS platforms. I want to check for internet connectivity on Desktop, Android, and iOS devices. I've read about three different solutions:


  1. Ping某事(例如谷歌) - 我完全不喜欢这样的决定,而我已经读过Android上的错误。

  1. Ping something (for example Google) - I totally dislike such decision, and I've read about mistakes on Android.

Application.internetReachability - 根据Unity的文档,此功能只会确定我有可能连接到互联网(它不保证真正的连接)。

Application.internetReachability - According to Unity's documentation, this function will only determine that I have a POSSIBILITY of connecting to the Internet (it doesn't guarantee a real connection).

网络。 TestConnection() - 如果我没有Internet连接,我的应用程序将失败。所以这也不正确。

Network.TestConnection() - If I have no Internet connection, my application fails. So this isn't correct either.

如何确定我是否从Unity内部连接互联网?

How can I determine whether I have internet connectivity from within Unity?

推荐答案

我实际上并不认为 Network.TestConnection()是这项工作的正确工具。根据文档,它看起来像是用于测试NAT是否是工作和您的客户端可通过IP公开访问,但您要检查的是您是否具有一般的互联网连接。

I don't actually believe that Network.TestConnection() is the right tool for this job. According to the documentation, it looks to me like it's meant for testing if NAT is working and your client is publicly reachable by IP, but what you want to check for is whether you have general internet connectivity.

这是一个解决方案users / 393647 / pixel-fiend.htmlrel =noreferrer> pixel_fiend ,它只是测试一个网站,看看用户是否有连接。此代码的一个好处是它使用 IEnumerator 进行异步操作,因此连接测试不会占用应用程序的其余部分:

Here is a solution that I found on Unity Answers by user pixel_fiend, which simply tests a website to see if the user has connectivity. One benefit of this code is that it uses IEnumerator for asynchronous operation, so the connectivity test won't hold up the rest of your application:

IEnumerator checkInternetConnection(Action<bool> action){
     WWW www = new WWW("http://google.com");
     yield return www;
     if (www.error != null) {
         action (false);
     } else {
         action (true);
     }
 } 
 void Start(){
     StartCoroutine(checkInternetConnection((isConnected)=>{
         // handle connection status here
     }));
 }

您可以将网站更改为您想要的任何内容,甚至可以将代码修改为如果可以访问多个站点中的任何一个,则返回成功。 AFAIK无法在不尝试连接到互联网上的特定网站的情况下检查真正的互联网连接,因此ping这样的一个或多个网站可能是您确定连接时的最佳选择。

You can change the website to whatever you want, or even modify the code to return success if any one of a number of sites are reachable. AFAIK there is no way to check for true internet connectivity without trying to connect to a specific site on the internet, so "pinging" one or more websites like this is likely to be your best bet at determining connectivity.

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

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