Raycast is not working properly

Hi. Can anybody please check what is wrong in this script? I have been trying to fix it for 2 hours, and I just gave up.

using UnityEngine;
using System.Collections;

public class ai1 : MonoBehaviour {

	public float spottingDistance = 1;

	bool canSee;
	bool alerted=true;

	NavMeshAgent pathfinding;
	GameObject player;

	RaycastHit hitInfo;

	void Start(){
		pathfinding=GetComponent<NavMeshAgent>();
		player = GameObject.FindGameObjectWithTag("Player");

	}

	void Update(){


		Physics.Raycast(gameObject.transform.position, player.transform.position, out hitInfo, spottingDistance);
		Debug.DrawRay(gameObject.transform.position, player.transform.position, Color.cyan);

		if(hitInfo.transform.tag=="Player"){
			canSee=true;
		}
		else{
			canSee=false;
		}

		

		if(canSee){
			Debug.Log("Enemy is shooting");
		}
		else if(alerted){
			Debug.Log("Enemy is following");
			pathfinding.SetDestination(player.transform.position);
		}

	}
}

This is what’s wrong:
[35623-the+hell.jpg|35623]

The problem with your script is that although you are supplying two Vector3 variables, the second variable needs to be the direction, not the position that you are aiming for.

You need to create the direction.

Assuming the player is at the point of origin you would do this:

Vector3 dir = (gameObject.transform.position - player.transform.position).normalized;

Alternatively, if the gameObject is the origin, then reverse:

Vector3 dir = (player.transform.position - gameObject.transform.position).normalized;

Then

Physics.Raycast(gameObject.transform.position, dir, out hitInfo, spottingDistance);

Have you tried making it in an if statement?

using UnityEngine;
 using System.Collections;
 
 public class ai1 : MonoBehaviour {
 
     public float spottingDistance = 1;
 
     bool canSee;
     bool alerted=true;
 
     NavMeshAgent pathfinding;
     GameObject player;
 
     RaycastHit hitInfo;
 
     void Start(){
         pathfinding=GetComponent<NavMeshAgent>();
         player = GameObject.FindGameObjectWithTag("Player");
 
     }
 
     void Update(){
 
 
         Debug.DrawRay(gameObject.transform.position, player.transform.position, Color.cyan);
 
         if(Physics.Raycast(gameObject.transform.position, player.transform.position, out hitInfo, spottingDistance)){
             if(hitInfo.transform.tag=="Player"){
                 canSee=true;
             }
             else{
                 canSee=false;
             }
         }
 
         
 
         if(canSee){
             Debug.Log("Enemy is shooting");
         }
         else if(alerted){
             Debug.Log("Enemy is following");
             pathfinding.SetDestination(player.transform.position);
         }
 
     }
 }