[MenuItem("Tools/Read file")]
static void ReadString()
{
string path = "Assets/Resources/Map File.txt";
//Read the text from directly from the test.txt file
StreamReader reader = new StreamReader(path);
reader.Close();
}
I want to make my string equal to the first line for example.
string name = reader.FirstLine();
How can i do it?
So the thing about reading files is that you don’t usually keep moving around it, you read it once and put it in memory. And then you read directly from memory.
In your case you probably want to read the entire file, putting the contents on each line, making a list of string and then reading from it.
instead of string firstLine = reader.ReadLine(); you want this:
string line = "";
List<string> lines = new List<string>();
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
I actually wanted the opposite!
I want to load a text file only when i need.
I make a map generator based on numbers.
Only one string is needed that collect the line that i want.
I really would like to point out the very bad performance of text files. If you can, convert them to either binaries or to serialized data-structure as soon as possible (if they come from outside source, if you produce them in the editor, highly advisable to go serialized instead).
This applies to any kind of text file, jsons and XMLs included.
Don’t really care about memory in the editor (unless you have a huge database → gigabytes, but in that case you really should not play around with text files), just read up all of it. In run-time, you should use serialized parts and either the whole thing or split up to parts, but stay serialized. You can load assets manually.
I thought that the performance will be better with text files.
So you say List of strings will do the job better?
And what about a long string that include all?
for example:
only one string needed here, just replacing the details.
text files require the system to reaching out to the OS to access other areas of the computer, it involves a LOT of things in the background, hence the performance loss when dealing with text files rather than directly from your local app memory.
Since you want to save a map into a file, it doesn’t matter if you have it s a list of strings or a single string, that will be just a temporary phase of the file converting to and from the file. What matters is that you have your map (probably a tile map) as an array of 2 dimensions(or the likes of it) when accessing from your app local methods.