Hello, i added two colliders to my 2D player. but when the player touch an enemy it takes 2 hearts from his life. that because the enemy is colliding with two different colliders. how can i solve this problem?
here is the code :
if (gameObject.CompareTag(“Enemy”) && playerHealth > 0)
{
if (doubleJump > 0 && rb.velocity.y < 0)
{
kills++;
Destroy(gameObject);
return;
}
else
{
playerHealth–;
return;
}
}
2 different things come up to me
First You may seperate your collider with a child object and add a collider and tag two different collider differently and maybe use that Code; (I assume you put this script on the player)
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Enemy") && playerHealth > 0)
{
if (doubleJump > 0 && rb.velocity.y < 0)
{
kills++;
other.gameObject.GetComponent<Collider>().enabled = false;
Destroy(other.gameObject);
}
else if (gameObject.CompareTag("Tag you want to collide with enemy"))
{
playerHealth--;
}
}
It may be worth looking into using a CompositeCollider2D instead of worrying about two separate colliders both triggering collisions as use could use the single CompositeCollider2D object in your logic instead. You can keep your original colliders in place, just set their “UsedByComposite” property to true and they should automatically get incorporated into the composite collider.