Hi. I’m working on a game where it reads info from a file and overwrites the file whenever i need it to. For some reason (which i dont know what the reason is), blank lines keep “spawning” in the .txt file. Heres some of the code. I hope this helps:
function Start () {
var sr = File.OpenText("Assets/XXXXX/Files/charactersHealth.txt");
fileLines = sr.ReadToEnd().Split("
"[0]).ToList();
sr.Close();
}
function OnCollisionEnter (col : Collision) {
var sr = File.OpenText("Assets/XXXXXX/Files/charactersHealth.txt");
fileLines = sr.ReadToEnd().Split("
"[0]).ToList();
sr.Close();
WriteHealth();
}
function WriteHealth () {
var ar = fileLines.ToArray();
if (transform.parent.name == "XXXXX") {
ar[0] = health.ToString();
}
if (transform.parent.name == "XXXX") {
ar[1] = health.ToString();
}
File.WriteAllLines("Assets/XXXXXX/Files/charactersHealth.txt", ar);
}
// Some personal info is blanked out with X's
Also, other scripts with kind-of the same type of code is accessing the same file as the code above is.
There is no “bug” in a txt file and also not in the File class. Everything works as it should. The problem here is that you use “WriteAllLines” which usually uses windows line endings (CR + LF). Since you split your text manually on LF () the CR (\r) will remain in the text and will be written to the file as additional lines.
The File class has a lot quite useful static functions like File.ReadAllLines() and File.WriteAllLines. I’m not sure why you use a File object to read the file and WriteAllLines to write the file.
So just use File.ReadAllLines() to read the file and everything should be fine.