using System; using UnityEngine; public class InternetCheckSystem : MonoBehaviour { public event Action OnCheckSuccess; public event Action OnCheckFailed; [SerializeField] private string pingAddress = "8.8.8.8"; [SerializeField] private float pingTimeOut = 2f; [SerializeField] private int pingRetries = 3; private Ping _ping; private int _pingCount; private float _startTime; private bool _isPinging; public void CheckInternet() { _ping?.DestroyPing(); if (_pingCount >= pingRetries) { Debug.Log("** Connection Unavailable!"); OnCheckFailed?.Invoke(); OnCheckFailed = null; return; } _ping = new Ping(pingAddress); _isPinging = true; _startTime = Time.time; _pingCount++; Debug.Log($"ping [{_pingCount}] has started"); } private void Update() { if (!_isPinging) return; Debug.Log("ping on-going..."); // Debug.Log($"StartTime: {_startTime}, CurrentTime: {Time.time}"); if (Time.time >= _startTime + pingTimeOut) { Debug.Log($"ping [{_pingCount}] time out"); _isPinging = false; CheckInternet(); return; } if (!_ping.isDone) return; if (_ping.time <= 0) return; _isPinging = false; Debug.Log("** Internet Available!!!"); OnCheckSuccess?.Invoke(); OnCheckSuccess = null; } }