So I’m working on a very basic app that requires basic networking. I am specifically getting an issue where if the client running in Unity cannot connect to the server the unity application crashes. This happens both in the editor and in a build. I’m not fully sure why this would happen, because the code that I believe is causing the error is inside a try-catch statement. The other important thing to note is that I am currently running the server locally, and when the server is running the app performs as expected, its only when the server is not initialized or unreachable that the project crashes.
The code below is only referencing the important details, but if the whole scripts are needed I can add them.
MainScript.cs:
//referenced by login button
public void AttemptLogin()
{
GameObject usernameInput = SplashScreen.transform.GetChild(2).gameObject;
string username = usernameInput.GetComponent<TMP_InputField>().text;
GameObject passwordInput = SplashScreen.transform.GetChild(3).gameObject;
string password = passwordInput.GetComponent<TMP_InputField>().text;
loggedInUsername = username;
if (username == null || password == null || username == "Username" || password == "Password")
{
Error("username or password null on login");
return;
}
loggedInUsername = username;
fileManagerCS.AttemptLogin(username, password);
}
FileManager.cs
public void AttemptLogin(string username, string password)
{
try
{
client = new TcpClient(ServerAddress, Port);
networkStream = client.GetStream();
reader = new StreamReader(networkStream, Encoding.UTF8);
writer = new StreamWriter(networkStream, Encoding.UTF8) { AutoFlush = true };
// Send username and password
writer.WriteLine(username);
writer.WriteLine(password);
// Receive authentication result
int authResult = int.Parse(reader.ReadLine());
if (authResult == 1)
{
isConnected = true;
mainScriptCS.OpenMain();
}
else
{
isConnected = false;
mainScriptCS.Error("Incorrect username or password");
CloseConnection();
}
}
catch (Exception ex)
{
mainScriptCS.Error("Error during login: " + ex.Message);
CloseConnection();
}
}
So far I’ve tried to run the AttemptLogin() method as an asynconous task, but that just led to the whole project crashing whenever the method was called. I’ve also tried to output mutliple debug statements but I can’t see them before the unity editor crashes, so I don’t actually know which line is causing the error, nor why the catch statement doesn’t stop the crash.
I’m mainly posting this here because I don’t know how to fix the crashing issue, but if my way of networking isn’t the most elegant and there is a better option then I’ll rework the whole system to make it work.