I looked around for a long time for the solution to this and wound up solving it right before I clicked post, so here's the answer for anyone else having the same problem:
In loading from a file, I was splitting the text by the newline \n
character -
string[] lines = fileData.Split('\n');
The problem is that, on Windows systems, new lines are defined by the carriage return/line feed sequence.
So, while splitting on \n
was/is splitting each line at approximately the correct location, <string>.Split('\n')
leaves a carriage return on the end of each resulting string. That carriage return does not display in debug messages.
Instead of trying to find the tag MainCamera
, I was actually trying to find the tag MainCamera\r
which does not actually exist.
I found this when putting in "MainCamera"
worked but the data loaded from file did not. I used the following code to debug:
string output = "Hex string:";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(lineFromFile);
foreach(byte currentByte in bytes)
{
output += " " + System.Convert.ToString(currentByte, 16);
}
Debug.LogFormat("lineFromFile string is {0}; converts to {1}.", lineFromFile, output);
For a line from file that read MainCamera
, this produced:
lineFromFile string is MainCamera; converts to Hex string: 4d 61 69 6e 43 61 6d 65 72 61 d.
Note the d
at the end of that line!
Going to an ASCII lookup table gives 0D
to be the carriage return operator.
So, ultimately, I think a good way to split a file into lines is to replace all the Windows-style line endings, \r\n
, with the Unix-style (and maybe Mac-style?) \n
line endings, then to split the file on the \n
. In this way, if you're on a Unix system, the Replace command just returns the original string (because it didn't find any \r\n
sequences), and then for both systems you're breaking the lines correctly.
string fileData = File.ReadAllText(filename);
string[] lines = fileData.Replace("\r\n", "\n").Split('\n');