when my raycast hits the enemies freeze

I’m making a top down shooter and I’m using Ray cast to be fired from the enemy to the player but when I test the game and I get in the range of the enemy to either attack or chase me they just freeze up. and if I’m completely out of their range they walk around like they should. This is my first time using ray casts so I’m not sure if I did something wrong.
here is my code:

    Vector3 startRay = transform.position;
    Vector3 rayDirection = player.transform.position;
    RaycastHit hit;

    //Check for sight and attack range
    playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
    playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);

    if (!playerInSightRange && !playerInAttackRange)
    {
        Patroling();
    }
    if (playerInSightRange && !playerInAttackRange && Physics.Raycast(startRay, rayDirection, out hit, sightRange))
    {
        if (hit.collider.tag == "Player")
        {
            ChasePlayer();
        }
    }
    if (playerInAttackRange && playerInSightRange && Physics.Raycast(startRay, rayDirection, out hit, attackRange))
    {
        if (hit.collider.tag == "Player")
        {
            AttackPlayer();
        }
    }

My ChasePlayer function:

private void ChasePlayer()
{
agent.SetDestination(player.position);
}

my AttackPlayer function:

private void AttackPlayer()
{
agent.SetDestination(transform.position);

    transform.LookAt(player);

    if (!alreadyAttacked)
    {
        Instantiate(projectile, transform.Find("BulletSpawn").position, 
        transform.Find("BulletSpawn").rotation);

        alreadyAttacked = true;
        Invoke(nameof(ResetAttack), timeBetweenAttacks);
    }
}

Hi, the Raycast will probably never hit the player. The second parameter to the Physics.Raycast is direction not destination. Direction is a vector pointing from the origin in the direction of the destination. So change it to Vector3 rayDirection = player.transform.position - transform.position; Now it should hit the player if there is no obstacles between the enemy and the player. So the freezing as you see is probably just standing still because the Raycast never hits.


Recommendation: Its better to avoid expensive method calls such as Physics.CheckSphere or Physics.Raycast whenever you can. You can check the distance directly without using Physics.CheckSphere by playerInAttackRange = Vector3.Distance(transform.position, player.transform.position) < attackRange. Its much faster. The Physics.Raycast is probably necessary here just Physics.Linecast can be little bit faster. Actually Physics.Linecast has second parameter destination so you can just change it to Physics.Linecast instead of Physics.Raycast.