Search Unity

Question Prevent errors when the player is not connected to the internet

Discussion in 'Netcode for GameObjects' started by GuirieSanchez, Jan 18, 2023.

  1. GuirieSanchez

    GuirieSanchez

    Joined:
    Oct 12, 2021
    Posts:
    452
    What's the best way to detect and prevent errors when players aren't connected? In order not only to prevent them but also to be able to display a warning message and whatnot.

    If I try to connect while not connected to the internet / WiFi, I get this error:
    upload_2023-1-18_20-58-51.png

    "WebException: Error: NameResolutionFailure
    System.Net.WebConnection.Connect (System.Net.WebOperation operation, System.Threading.CancellationToken cancellationToken) (at <9fe598e1f1334abeae4ea9fbbe948c3e>:0)"

    It points to a place in the code where I try to get the public IP:

    Code (CSharp):
    1. public static string GetPublicIPv4()
    2.         {
    3.             var ipString = new WebClient().DownloadString("http://icanhazip.com");
    4.             return ipString.Replace("\\r\\n", "").Replace("\\n", "").Trim();
    5.         }
    What bothers me about this exception is that it freezes the game: It still runs but the buttons do not respond.

    I don't know if this is the only piece of code that might cause an issue (I'm connecting players locally). But I think it'd be nice to have a way to detect if there's a connection available and only allow the networking code to run when they're connected.

    Any piece of advice is highly appreciated.
     
    Last edited: Jan 18, 2023