- Home /
Tag comparision with a string as variable doesnt work
very simple: I get the other as a string and if that string is equal to the tag of the player it should do smoething
private void TakeDamage(string other){
Debug.Log(Player.tag + " " +other);
if(Player.tag == other){
Debug.Log("attack player");
}
}
The Debug.Log shows that both strings (tag and other) er exactly the same. But it just doesnt work. I tried it with Player.CompareTag and got the same result.
this is the Debug.Log:
tps_player tps_player (UnityEngine.GameObject) UnityEngine.Debug:Log(Object)
Answer by yoyo · Mar 23, 2011 at 03:13 PM
The existence of the CompareTag method suggests that tag strings may be stored in a way that doesn't work properly for normal string comparison.
Try this:
if(Player.CompareTag(other))
...
If that doesn't work, you could inspect the bytes of each string with a method like this:
void LogStringChars(string s)
{
string msg = s + "=(";
foreach (char c in s)
{
msg += (int)c + ",";
}
msg += ")";
Debug.Log(msg);
}
Just add the following to your method ...
LogStringChars(Player.tag);
LogStringChars(other);
well, that was my first attempt. but as I said it doesnt work with compareTag either. I get this error message when using comparetag
UnityException: Tag: tps_player (UnityEngine.GameObject) is not defined! EnemyAI.TakeDamage (System.String other) (at Assets/...
Sorry, obviously I read too quickly and missed that you'd already tried that. I edited my answer with another suggestion. Weird problem, good luck!
Answer by Bunny83 · Mar 23, 2011 at 12:12 PM
The tag of a GameObject is just a string, so that comparison will work if they are equal. since it doesn't work they are not equal. Maybe a space at the end?
ps. what does tps
stand for? you don't wan't to write fps
?
There are no spaces or what ever. and the debug shows that they should be exact the same. the t stands for THIRDperson ;)
Answer by User12345 · Mar 24, 2011 at 12:25 AM
Ok I found another way... or... I probably found the main problem.
the "other" string I sent was actually the name of a gameobject (I used gameObject.ToString(); to convert)that had the same name as the tag! Somehow unity makes a difference between strings and their origin.
So what I did now was to send the gameobject.tag instead of the gameobject.ToString(); which would have been the most logical in the first place... dont know what I was thinking there -.-
Even scarier - ToString adds on the type. If you want the name of a gameobject, use go.name
Answer by Rafes · Jul 30, 2011 at 05:54 PM
If you want to know if something is a specific game object, you can test if the gameObject is equal to the other gameObject.
Tags are good for testing if the hit item is part of a group of things.