📜  c# unity get lines - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.426000             🧑  作者: Mango

C# Unity Get Lines

Have you ever needed to get the number of lines in a file in your Unity project? Perhaps you're trying to automate some process or maybe you're just curious. Either way, here's how to do it in C# Unity.

First, we need to create a reference to the file we want to count the number of lines in. Here's an example:

string filePath = Application.dataPath + "/Example.txt";

In this example, we're using the Application.dataPath property to get the path to the Assets folder in our Unity project. Then, we're appending the name of the file we want to reference, which is Example.txt.

Next, we need to create a StreamReader instance to read the file:

StreamReader reader = new StreamReader(filePath);

Now that we have a reference to the file and a way to read it, we can count the number of lines. There are a few different ways to do this, but one easy approach is to use a while loop to read each line of the file and increment a counter until we've reached the end of the file:

int lineCount = 0;
while (reader.ReadLine() != null) {
    lineCount++;
}

Finally, we need to close the StreamReader when we're done with it:

reader.Close();

Here's the complete code, all together:

string filePath = Application.dataPath + "/Example.txt";
StreamReader reader = new StreamReader(filePath);
int lineCount = 0;
while (reader.ReadLine() != null) {
    lineCount++;
}
reader.Close();

And that's it! With this code, you can get the number of lines in any file in your Unity project.