以下只能识别到是否连接到网络,但是不清楚能否联通
Application.internetReachability == NetworkReachability.NotReachable
NotReachable 网络不可达
ReachableViaCarrierDataNetwork 网络通过运营商数据网络是可达的。
ReachableViaLocalAreaNetwork 网络通过WiFi或有线网络是可达的。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AoniMapDownloadItemView : MonoBehaviour
{
bool isOnline = false;
public Button test;
void OnEnable() {
test.onClick.AddListener(OnBtClick());
}
public UnityAction OnBtClick()
{
// check whether or not connect internet
StartCoroutine(CheckInternetConnection((startTime, online) =>
{
Debug.LogFormat("连接状态:[{0}] 耗时:{1}", online, Time.time - startTime);
isOnline = online;
if (online)
{
// 成功操作
}
else
{
// 失败操作
}
}));
return null;
}
public IEnumerator CheckInternetConnection(Action<float, bool> onDone)
{
float startTime = Time.time;
using (UnityWebRequest www = UnityWebRequest.Get("http://baidu.com"))
{
yield return www.Send();
if (www.isError)
{
Debug.LogFormat("internet error:{0}", www.error);
onDone(startTime, false);
}
else
onDone(startTime, true);
}
}
}