Navmesh Agent - stop after player out of range

Hi guys

So I’m making a horror game, and i have an enemy which normally hangs around the place, but when you get closer he will get “aware” of you. If you go even closer, he will begin chasing you around the map. I’m using the Navmesh to find the way around the map, and it’s working perfectly. However my problem is that after the isn’t chasing me anymore because I’m out of range, he switches back to the alarm animation but still slides to my last known position. I provide the code below. Please help me, I tried to solve the problem alone, but I’m still new to programming :slight_smile:

var Distance;
var Target : Transform;
var lookAtDistance = 25.0;
var chaseRange = 15.0;
var attackRange = 5.0;
var Damping = 6.0;
var attackRepeatTime = 1;
var TheDammage = 40;
var model : Transform;

private var agent: NavMeshAgent;
private var attackTime : float;

function Start ()
{
	agent = GetComponent.<NavMeshAgent>();
}

function Update ()
{
	if(RespawnMenu.playerIsDead == false)
	{
		Distance = Vector3.Distance(Target.position, transform.position);
		
		if (Distance < lookAtDistance)
		{
			lookAt();
		}
		
		if (Distance > lookAtDistance)
		{
			model.animation.CrossFade("Idle");
		}
		
		if (Distance < attackRange)
		{
			attack();
		}
		else if (Distance < chaseRange)
		{
			model.animation.CrossFade("Attack");
			chase ();
		}
	}
}

function lookAt ()
{
		var rotation = Quaternion.LookRotation(Target.position - transform.position);
		transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);	
		model.animation.CrossFade("Aware");
	}

function chase ()
{
	agent.SetDestination(Target.position);
	renderer.material.color = Color.red;
}

function attack ()
{
	if (Time.time > attackTime)
	{
		Target.SendMessage("ApplyDammage", TheDammage);
		Debug.Log("The Enemy Has Attacked");
		attackTime = Time.time + attackRepeatTime;
	}
}

function ApplyDammage ()
{
	chaseRange += 30;
	lookAtDistance += 40;
}

You must call agent.Stop in order to stop his movement.