so i have this code that i’m using the same for bullets and it works fine but when i’m using it on the player it doesn’t work. i just want the player to get destroyed when the enemy collides with him.
the problem is that the collision isn’t working cuz i used debug.log and it didn’t appear in my console.
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag.Equals("Enemy"))
{
Destroy(gameObject);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.tag == “Enemy”)
{
Destroy(gameObject);
Debug.Log(“You are killed by your enemy!”);
}
}
Here just add this to your player and tag your enemy as “Enemy”. And let me know if it works
I assume you are working on a 2D project, because the methods you’d use would be different in 3D. But anyway…
Always check these:
- Check if there is any spelling mistake in your tag and in your code, and remember they are case sensitive.
- Remember that your player needs a Collider2D component (so Box Collider 2D for example) that acts as a trigger (check the “Is Trigger” box) and a Rigidbody component.
- Also, the enemy needs at least a Collider2D component, and it needs to be tagged.
Also, as good practice, try to use collision.gameObject.CompareTag("Enemy")
.
I hope this helps. @SHaRKkon
Adding my comment as an Answer, so it can be tagged as the best answer, per SHarKkon’s comment
First off, when putting code in your question, please use the “101/010” button so the code is formatted to be more readable.
Make sure that both the enemy and the player have a Collider2d component, and that at least one of them have a RigidBody2D component.