- Home /
Display a loading while processing a while loop
Hello, In one moment of my game, the player is able to import a file to the game. That's the function that read each line of the file:
void readTextFile(string file_path) { StreamReader inp_stm = new StreamReader(file_path);
while (!inp_stm.EndOfStream)
{
string inp_ln = inp_stm.ReadLine();
print(inp_ln);
// Do Something with the input.
}
inp_stm.Close();
}
The problem is that when import a huge file, it takes almost 3 minutes to read it, so it looks like it stoped responing, but is acctually processing the file. So, I would like a loading dialog to show the user that the application did not stop. But how I do that if the application is tied in the "while"? Thanks.
Answer by fafase · Oct 21, 2015 at 01:39 PM
StreamReader is working in one run so you cannot cut it in sub section.
You'd be better off trying with WWW class using a local url. Then you can yield and animate something in the meanwhile.
I'm not familiar with this class. Could you explain more?
That's what i got so far:
IEnumerator readTwo(string file_path)
{
WWW www = new WWW("file:///" + file_path);
yield return www;
//print(www.text);
print(www.text);
}
But it reads all the docmunt once, and not line by line. But it runs faster than the other method. But, it still stops responding while processing.
Yes the result is one file. If you need to cut it by lines then you need to perform that action yourself:
string[] lines = www.text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
the WWW class is meant to process HTTP requests (GET/POST). The argument is the url, that one can be a server location or a local file.
It does not read line by line, but your original code did not either. It loads the whole into a buffer and converts it into a string array. Then you are reading line by line.
IEnumerator readTwo(string file_path)
{
WWW www = new WWW("file:///" + file_path);
yield return www;
string[] lines = www.text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach(string line in lines)
{
Debug.Log(line);
yield return null;
}
}
The code above will load the file asynchronously, that means it processes a bit (maybe on local file it does the whole thing at once, dunno) and returns control, then processes a bit more and so on until all done.
Once you get the whole file done, the Split method cuts it. The foreach loop runs through the array and returns the control to the app on each line.
As a result, you can have other scripts perfor$$anonymous$$g action in the middle.
Your answer
Follow this Question
Related Questions
Using a while loops to repeatedly execute a method? 2 Answers
Quaternion.Slerp issue 1 Answer
How to get something to be inactive while there is a certain value 2 Answers
Iterator variable not increasing. 1 Answer
While loop freezes unity 3 Answers