主要用到两个Unity的API:一个是Application.internetReachability,用来获取当前网络类型!需要注意的是,这里只是判断出来当前设备的网络环境,并不代表能连接到互联网上!是否能连接到互联网上需要通过下面的ping去操作!admin管理员组文章数量:1542731
使用方法如下:
if (NetWorkTxt != null)
{
if(Application.internetReachability == NetworkReachability.NotReachable)
NetWorkTxt.text = "当前网络:不可用";
else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
NetWorkTxt.text = "当前网络:3G/4G";
else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
NetWorkTxt.text = "当前网络 : WIFI";
}
另一个是Ping这个类,其实大多数人都会直接使用www去做了,但是这里用ping有个好处,就是你自己可以控制网络请求中断间隔时间,www默认的时间太长了,这里我使用2秒来作为检测时间,超过2秒就认为服务器无法访问!
使用方法如下:
C#
private void CheckResServerNetWorkReady ( )
{
StopCoroutine ( PingConnect ( ) ) ;
StartCoroutine ( PingConnect ( ) ) ;
}
IEnumerator PingConnect ( )
{
m_PingResServerState = PingState . PingIng ;
//ResServer IP
string ResServerIP = GetCurrentNormalIP ( ) ;
//Ping網站
Ping ping = new Ping ( ResServerIP ) ;
int nTime = 0 ;
while ( ! ping . isDone )
{
yield return new WaitForSeconds ( 0.1f ) ;
if ( nTime > 20 ) // time 2 sec, OverTime
{
nTime = 0 ;
Debug . Log ( "連線失敗 : " + ping . time ) ;
m_PingResServerState = PingState . CanNotConnectServer ;
yield break ;
}
nTime ++ ;
}
if ( ping . isDone )
{
yield return ping . time ;
m_PingResServerState = PingState . PingOK ;
Debug . Log ( "連線成功" ) ;
}
} 喜欢 2
版权声明:本文标题:网络:Unity3d检测当前网络环境wifi3G4G,以及对服务器的Ping操作 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1727079006a1096632.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论