Enemy looks for you, when he can't see you

Okay I have a script when you in the line of sight he will follow you, I am also using Nav Mesh.

What is want to do is, if the Enemy cannot see the player anymore I want it to look around for a certain amount of time then go back to its starting point.

var walkSpeed = 3;
var rotationSpeed : float = 3;
var runningSpeed : float = 6;

var player : GameObject;
var myTransform : Transform;
var target : Transform;
var fieldOfView : float = 50;
var rayRange : float = 10;

var distanceToStopRunning : float = 10;
var distanceToStopMoving : float = 3;
var detectFromBehind : float = 2;

var sneakingBehind = false;
var chasing = false;

function Awake(){
	myTransform = transform;
}

function Update(){

	var hit : RaycastHit;
	var rayDirection = player.transform.position - transform.position;
	var distanceToPlayer = Vector3.Distance(transform.position, player.transform.position);
	
	//Checks if to see if player is infront
	if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfView){
		if(Physics.Raycast (transform.position, rayDirection, hit, rayRange)){
			if(hit.transform.tag == "Player"){
				Debug.Log("Can see you MF");
				lookingAt = true;
			}
		}
	}
	
	if(lookingAt == true){
		chasing = true;
    }  	
  
		
	if(chasing == true){
		GetComponent(NavMeshAgent).destination = target.position;
		if(lookingAt == false){
			
			
			
		}
	}
}

function OnDrawGizmosSelected(){
	Gizmos.color = Color.green;
	Gizmos.DrawRay (transform.position, transform.forward * rayRange);
}

Thanks for the help.

I won’t write the entire thing for you, but you’re pretty close.

You’re already checking if the enemy can see you with the ray cast. However, if they can’t, you’re not starting a timer–which is what needs to happen. If they CAN see you, the timer needs to be set again to zero.

If the timer gets above whatever value you want, then that’s when you can restart your enemy, so to speak.

Almost there, the hard part is done.

On a side note, to help clean your code up a bit, I would suggest changing your boolean checks from:

if(chasing == true)

to

if(chasing)

It’s less code, means the same, and you’ll find out quick that the less code you can write (usually) the more readable (and therefore maintainable) your code base is.