OnTriggerEnter2D() function not working
I have a player object that has a box collider 2d and a rigid body 2d, this is set to simulated and to dynamic. Then I have another object that has a box collider where is trigger is ticked, I have also added a rigid body 2d to this object, however, I don't think it actually makes a difference if I have it or not. (both rigid bodies are simulated and dynamic) Then on my player character, I have the code :
private void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Box")
{
Debug.Log("No");
}
}
The weird thing is if I get rid of the if statement then the console writes out No, so doesn't that mean that all the box colliders and rigid bodies work? I'm new to unity so I have no idea. I hope someone can help a fellow new beginner out :)
Is the box properly tagged in the exact same way as the String says...aka "Box"...also, instead of using ==, use CompareTag....
if(col.gameObject.CompareTag("Box"))
as you already mentioned, OnTriggerEnter is working totally fine, so the problem lies in the if() statement...most likely it's the tag, and i believe implementing both of the fixes i mentioned should do...hope this helps
Answer by Marioooo · Aug 11, 2021 at 06:58 PM
Hi!
first of all, have you set the "box" gameobject a tag called "Box"? that's the most common mistake.
Second, you shoudn't use that way to compare a tag, instead use
if(col.gameObject.CompareTag("Box"))
this approach is better cause is faster, mostly if you check a lot of collisions
Hope this helps! Good Luck!
Your answer
Follow this Question
Related Questions
OnTriggerEnter2D not working 2 Answers
Coin Magnet Collider Overlap 0 Answers
How to make a growing mesh 0 Answers
OnTriggerEnter2D Not Detecting BoxCollider2D - Childed Object 2 Answers
My enemies wont move! 0 Answers