- Home /
CompareTag doesn't work
Hi everyone, i wrote a code, it detect colliders and add in list "side", but then i trying to compare it with tag, i always get false, could someine give an advice?
Collider[] side; bool Obstacle; ..... void Update { if (Attached)
{ side = Physics.OverlapSphere(transform.position, 0.5f); foreach (var x in side) { Obstacle = x.CompareTag("Obstacle") ? true : false; } } }
Answer by Envans · Nov 26, 2020 at 06:51 PM
Check that object have the tag Obstacle, also spelling and case matters what I mean is obstacle != Obstacle that tag name must be the same for the objects as in the script you wrote.
Ok I didnt notice something, in your loop you check every collider hit so if you hit some obstacles but also something else and that something else is "later" in the list than the obstacle then the variable is set to false change your foreach loop code to this
Obstacle = false; foreach (var x in side) { if(x.CompareTag("Obstacle"){ Obstacle = true; return;} }
Answer by S-khan · Nov 26, 2020 at 07:02 PM
Debug your foreach loop, check you're getting your desired GameObjects. Also, check if you're getting any child that hasn't tagged yet. For debugging, put a Breakpoint on your foreach loop line and Attach to Unity. Make sure you're using vs2019.