Skip to content
Om Puter

Om Puter

Berbagi Tutorial Coding dan Pemrograman Komputer

Menu
  • Channel YouTube ThirteeNov
  • Channel YouTube Om Puter
Menu

Kode C# untuk Unity supaya kita bisa cek apakah user terhubung ke internet atau tidak

Posted on 10 Juni 2025 by OmPuter

Di bawah ini adalah kode C# yang jika dipanggil akan melakukan pengecekan apakah user terhubung ke internet atau tidak. Misal jika tidak terhubung, maka bukan scene game bernama “NoNet”

IEnumerator CheckInternetConnection()
{
    string[] testUrls = new string[]
    {
        "https://clients3.google.com/generate_204",
        "https://www.msftconnecttest.com/connecttest.txt",
        "https://www.cloudflare.com/cdn-cgi/trace"
    };
    float timeout = 5f;
    bool isConnected = false;

    foreach (string url in testUrls)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            webRequest.timeout = Mathf.CeilToInt(timeout);
            yield return webRequest.SendWebRequest();

#if UNITY_2020_2_OR_NEWER
            bool noError = webRequest.result == UnityWebRequest.Result.Success;
#else
            bool noError = !(webRequest.isNetworkError || webRequest.isHttpError);
#endif

            if (
                noError &&
                (webRequest.responseCode == 204 || webRequest.responseCode == 200)
            )
            {
                // Cek konten untuk msftconnecttest.txt
                if (url.Contains("msftconnecttest"))
                {
                    if (webRequest.downloadHandler.text.Trim() == "Microsoft Connect Test")
                    {
                        isConnected = true;
                        break;
                    }
                }
                else
                {
                    isConnected = true;
                    break;
                }
            }
        }
    }

    if (!isConnected)
        SceneManager.LoadSceneAsync("NoNet");
}
Post Views: 215

Kategori

  • 3D Max
  • Adobe Animate
  • Android
  • c#
  • Cordova
  • HTML5, CSS & JavaScript
  • iOS
  • Lain-lain
  • Photoshop
  • PHP
  • Python
  • Roblox
  • Tak Berkategori
  • Unity
  • WordPress
ciihuy2020
© 2026 Om Puter | Powered by Superbs Personal Blog theme