Using collider to gameobject detect attack or not

I am using collider to detect the monster in player attack area or not.

And also, to detect the player in monster attack area or not.

But the problem is that will also triggering the monster “OnTrigerEnter2D” when monster going in player collider area. (player is not in monster collider area)

it mean the trigger will be triggered by other gameobject collider?

How can i fix that? Or i should not use collider to do that?

If you really want to do that with colliders, you would need to go with 2 colliders per entity. So the player has a small collider which can be detected by the monster’s big radius collider, and the monster has a small collider that can be detected by the player’s big radius collider.

I would recommend using Vector3.Distance though and checking if the monster is in the player’s attack range and vica versa.

Example::

public class Player : MonoBehaviour
{
    public Transform monster;
    public float attackRange = 3;

    void Update()
    {
        if(Mathf.Abs(Vector3.Distance(transform.position,    monster.position)) < attackRange)
        {
            // Monster is in attack range of player, do your stuff
        }
    }
}

I already fix the problem.

The first point is as @Cence99 said, I need to use OnCollisionEnter2D instead of using OnTriggerEnter2D. Thanks a lot, @Cence99.


And, I changed the structure of the Player and Monster GameObject:

Player/Monster GameObject:

→ Body (RigidBody and Collider)

→ AttackArea (Kinematic RigidBody and Collider to detect monster target)


Last, using layer collision matrix to make both of the Collider in Body and AttackArea will not effecting the other one.