-1
\$\begingroup\$

I'm at a loss here because I'm not sure what's going on. I understand that tags need to exist first, and that you actually have to assign the tags after creating them, but GameObject.FindGameObjectsWithTag is not finding ANY tags, including the default tags.

If I try to find MainCamera, which is a built-in tag, I get the following error:

UnityEngine.UnityException: Tag: MainCamera is not defined. at (wrapper managed-to-native) UnityEngine.GameObject.FindGameObjectWithTag(string) at UnityEngine.GameObject.FindWithTag (System.String tag) [0x00002]

What do I do about this? The exact line of code throwing this exception is:

mountingObjects = GameObject.FindGameObjectsWithTag(attachesTo);

I'm trying to load tags from a file and it's not working.

\$\endgroup\$

1 Answer 1

-1
\$\begingroup\$

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');
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .