Make AI attack on sight, otherwise go to another target.

I have a AI walking towards a moving target at all time which I made work by the code in the else-statement but when I add a raycast to make the AI see the player both the players and the AI’s mesh is bugged and wont move nor make the animations that it did before. Here is the code I’m using now

var target : Transform;
var player : Transform;
var source : Transform;

var hit : RaycastHit;

function Update () {
	
	if(collider.Raycast(new Ray(source.transform.position, Vector3.forward), hit, 10.0)){
		
		if(hit.transform.tag == "player"){
	
			GetComponent(NavMeshAgent).destination = player.position;
			
		}
		
	}
	
	else{
	
		GetComponent(NavMeshAgent).destination = target.position;
		
	}
	
}

which is really small and simple but I don’t seem to find what I’m missing and can’t see why this affects the mesh rendering.

Are you trying to pick towards the player or only directly in front of the AI entity? If you’re trying to pick towards the player the ray should be:

Ray ray = new Ray(transform.position, (player.transform.position - transform.position).normalized);

If you want to pick directly in front of the AI entity, the ray should be:

Ray ray = new Ray(transform.position, transform.forwards);

Be mindful that ‘if(Physics.Raycast)’ will return the FIRST collider it hits, so if your AI entity has colliders and you don’t use a layer mask when raycasting, you may just be hitting the AI entities’ collider.

Also, are you sure 10 far enough for the ray cast and have you checked that the raycast is hitting the player? Use the following line inside a successful raycast to check:

Debug.Log(hit.collider.tag);