So I was following a tutorial, where we make a sword attached to the player character and when the sword touches the enemy, the enemy object got destroyed. However, I made a mistake while following the tutorial, and it causes both the player and enemy to get destroyed when the sword touched the enemy.
Below is the correct code, when I use this code only the enemy is destroyed
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy(other.gameObject);
}
}
Below is the wrong code I used, which cause both the player and enemy to get destroyed
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy(other.gameObject);
}
}
I tried to search the difference between Collision and Trigger, and the only answer I found is that Trigger can be permeated by other object unlike collision. But I don’t think that answer the question on why when I use OnCollisionEnter both player (including the sword which was a child object of the player) and the enemy got destroyed, while only the enemy got destroyed when using OnTriggerEnter. Can anyone explain why?