Raycast2D Not Working With CompareTag

So I want a raycast to use compareTag but it doesn’t seem to work, Also the player is tagged correctly.
Thanks in advance.

void DetectionF(float distanceToTarget)
{
float angle = Vector2.Angle(vision, target.position);
if (lastAngle!=angle)
    Debug.Log("Angle: " + angle);
lastAngle = angle;


Debug.DrawLine(transform.position, target.position, Color.red, 0.2f);
if (70f< angle && angle<140f)
{
    RaycastHit2D hit = Physics2D.Raycast(transform.position, target.position, distanceToTarget);
    //This right here is where the problem lays
    if (hit.collider.gameObject.CompareTag("Player"))
    {
        player.detected = true;
        CancelInvoke("Undetect");
    }
}
}

In what way? Does it not enter the if? Please be more specific.

Firstly, you should always check if the hits collider is not null before running any kind of method on it. This is how you know you have hit something.

if(hit.collider != null)
{
    // Our raycast hit something
}

Please add some Debug Logs so you can actually follow the flow of code.
One within the if, so you know if it hits a GameObject tagged “Player”.
One before the if printing the tag of the hit object, so you can compare what is expected vs actual result.

In addition to checking that the collider isn’t null, the second part of the raycast2D should be a direction.