StreamReader in while loop stops/freezes unity

i am trying to make a script that checks if theres incoming data, using a while loop. but when i use the StreamWriter it waits until it receives data before continuing.

is there a way to let this run in the background instead of it blocking unity from rendering the game until it has received the data?

i had to Force quit unity for like 20 times since now, and I’m trying to find a solution

Current script:

void Read() {
	while(connection.Connected) {
		try {
			NetworkStream STREAM = connection.GetStream();
			StreamReader IN = new StreamReader(STREAM);
			string returndata = IN.ReadLine();
			string[] returndata2 = returndata.Split(" "[0]);
			string code = returndata2[0];
			string text = returndata.Replace(code, "");
			if(code == "#ChatMessage") {
				BroadcastMessage("AddChatMessage", text);
		catch (Exception c) {

If I’m not mistaken, ReadLine is waiting for a newline character, and that’s where it will hang. You could make this a coroutine (use yield). Or use Read and build up the buffer until you see a newline. Then either yield inside the loop you have, or put Read into an Update function instead.

solution: this post