Skip to content

Instantly share code, notes, and snippets.

@RimuruDev
Last active August 24, 2023 20:28
Show Gist options
  • Save RimuruDev/f4e4444c3b7d1442698f577d6a4a7ae0 to your computer and use it in GitHub Desktop.
Save RimuruDev/f4e4444c3b7d1442698f577d6a4a7ae0 to your computer and use it in GitHub Desktop.
⭐️Internet Connection Checker for Unity⭐️
// ReSharper disable All
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
//
// **************************************************************** //
using UnityEngine;
namespace RimuruDev.Codebase
{
public sealed class InternetCheckView : MonoBehaviour
{
public float checkInterval = 5.0f;
private InternetConnectionCheck InternetConnectionCheck;
private void Awake() =>
InternetConnectionCheck = new InternetConnectionCheck(this, checkInterval);
private void Start() =>
StartCoroutine(InternetConnectionCheck.CheckInternetConnection());
}
}
// ReSharper disable All
// **************************************************************** //
//
// Copyright (c) RimuruDev. All rights reserved.
// Contact me:
// - Gmail: rimuru.dev@gmail.com
// - GitHub: https://github.com/RimuruDev
// - LinkedIn: https://www.linkedin.com/in/rimuru/
//
// **************************************************************** //
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using System.Diagnostics.CodeAnalysis;
namespace RimuruDev.Codebase
{
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
public sealed class InternetConnectionCheck
{
private readonly string host;
private readonly float checkInterval;
private readonly MonoBehaviour coroutineRunner;
public bool IsConnection { get; set; }
public InternetConnectionCheck(MonoBehaviour coroutineRunner, float checkInterval = 5f, string host = "www.google.com")
{
this.host = host;
this.checkInterval = checkInterval;
this.coroutineRunner = coroutineRunner;
}
public IEnumerator CheckInternetConnection()
{
while (true)
{
coroutineRunner.StartCoroutine(PingHost());
yield return new WaitForSeconds(checkInterval);
if (IsConnection)
yield break;
}
}
private IEnumerator PingHost()
{
var request = new UnityWebRequest(host);
yield return request.SendWebRequest();
IsConnection = request.result == UnityWebRequest.Result.Success;
#if UNITY_EDITOR
Debug.Log($"<color=yellow>Internet Connection: {IsConnection}</color>");
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment