Player in front of enemy check not working, Physics.Raycast()?

This the game scene with two use cases as follows:

The player cannot be seen by the enemy:

172701-screenshot-100.png

The player can be seen by the enemy:

172702-screenshot-99.png

I am using the following code to decide whether the line of vision between the player and the enemy is clear for the enemy to attack, i.e., the enemy should only attack when there is no wall or any other collider between the player and the enemy:

void playerInRangeOfEnemy()
        {
            // After checking player is in range of the enemy, check for the line of vision between them
            Transform Player = FindObjectOfType<Player>().transform;
            Vector2 rayDirection = Player.position - transform.position; // --> transform.position is of the enemy
            RaycastHit hit;
            if(Physics.Raycast(transform.position, rayDirection, out hit, minAttackDistance))
            {        
                Debug.Log("Ray hitting the player"); // Not logging in either of the two cases mentioned above
                if (hit.collider.gameObject.CompareTag("Player"))
                {
                    // The following line is also not being logged
                    Debug.Log("Make the enemy attack the player");
                }
            }
        }

Both the enemy and the player are dynamic Rigidbodies. minAttackDistance is just the length of the raycast I want to cast, is set to 100 for now for testing.

How can I make the condition to be true so that both of the Logs are executed? Any updates to the above code?

Hello, are you using 3d object colliders for some reason? if not, you need to use the Physics2D method not the 3D one Unity - Scripting API: Physics2D.Raycast

Physics2D.Raycast(transform.position, rayDirection, out hit, minAttackDistance)