Why does GameObject.FindWithTag() get a wrong instance?
Hello, everyone.
I drag a player prefab into the hierarchy window to create a player instance. I name this instance "Player" and tag it "Player".
When I try to get this instance in my code, I find that GameObject.Find("Player") can get this instance, but GameObject.FindWithTag("Player") get a wrong instance. I use Debug.log() to print each result, the first one is: Player, and the second one is: Player(Clone).
Where does this Player(Clone) instance come from? Why does GameObject.FindWithTag() get the wrong instance?
Hope someone can help me.
Here is related code:
void Start()
{
GameObject a = GameObject.Find("Player");
GameObject b = GameObject.FindWithTag("Player");
Debug.Log(a);
Debug.Log(b);
}
$$anonymous$$ay we see your code that is causing the problem?
Answer by dan5071 · Feb 14, 2016 at 04:12 PM
I tried and was not able to replicate the error with the code that was given. The code you posted all looks perfectly valid to me, so I don't think it is actually your code that is causing the issue. Without seeing your project I can only guess, but I'd have to say one possibility is that you have another script that is instantiating a copy of the player, since this is usually how you get a GameObject(Clone) instance in your scene. Do you have any scripts that are instantiating anything? Even if you are not instantiating the player, it is possible that you accidentally changed the tag on a completely different game object, giving you two game objects with the "Player" tag. If you tried using GameObject.FindGameObjectsWithTag(), then it would return all the objects with the tag so you can see if there is more than one. I am not exactly sure what happens with GameObject.FindWithTag() when you have more than one object with the same tag, but I'd have to imagine it just picks the first one it finds.
Short Version: Test GameObject.FindGameObjectsWithTag() to see if you have more than one object with the "Player" tag.
Firstly, thank you for your answer.
After I asked this question, I continued to program other parts of my game and ignored this problem temporarily. After a while, the problem disappeared mysteriously (Both methods return the correct instance now). I cannot remember what I did clearly. $$anonymous$$aybe I missed something.
If I ever come across this problem again, I will try your suggestions for debugging.
Answer by gorbit99 · Feb 14, 2016 at 02:29 PM
Try flipping the two lines, so the findwithtag one is above the find one