- Home /
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) {
}
}
}
Answer by DaveA · Jun 18, 2012 at 07:38 PM
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.
Your answer
Follow this Question
Related Questions
Unity Webplayer doesn't work on Mac? 3 Answers
MonoDevelop from Unity 3.5 keeps freezing 2 Answers
A node in a childnode? 1 Answer
Unity crashing when I hit the Play button. 0 Answers
Unity freezes on Quit (4.3) 2 Answers