- Home /
If statement not working
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")
{
Destroy(gameObject);
//Debug.Log("OnCollisionEnter2D");
}
//Destroy(gameObject);
Debug.Log("OnCollisionEnter2D");
}
Answer by tokyomage · Dec 22, 2020 at 07:17 AM
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!
Your answer
Follow this Question
Related Questions
two if() statements with one GetKeyDown won't work. 1 Answer
Or in if statement (not working) 1 Answer
Monodevelop C# script execution bug 3 Answers
image click quiz button problem 0 Answers