Here is my 2D Game code and I want my circle game Object to destroy when it collides with objects with tag name = “Enemy”. Collision is detected when I comment out if statement but when I use if statement collision is not at all detected!! Please check my code and tell me if any error is present.
void OnCollisionEnter2D(Collision2D col)
if (col.gameObject.tag == "Enemy")
Some possible solutions:
- Make sure you’ve set the enemy GameObjects to actually use the “Enemy” tag and that it’s spelled in the Unity Editor Tags Manager exactly as you have it spelled here in your code.
- Additionally, you need at least one RigidBody2D component attached to one of the colliders in any collision between two colliders for an OnCollisionEnter2D event to be registered in the first place (which shouldn’t be the problem since you mentioned that you were able to at least detect collisions).
- Both objects that are colliding should exist in layers which can collide with one another, as dictated by the layer collision matrix found under Edit → Project Settings, in the “Physics” category. In your case you’ll most likely just want both objects that are colliding to be in the “Default” layer, which you can set for each respective GameObject.
I hope these suggestions help!