make animation stop when ai dosent have a target

Hi im looking for a way so that when my ai stops it goes back to idle animation

here is the current code

if (playerInSight == true)
			Player = FindClosestPlayer();
			PlayerT = Player.transform;
			var distance = Vector3.Distance(transform.position, PlayerT.transform.position);

			GetComponent<NavMeshAgent>().destination = PlayerT.position;
			animator.SetBool("walk", true);
			if (distance < Range)
				Attack ();
		if (DoWaypoints == true) 


I am going to edit the code that I got at the following source:

I figure this will better suite your needs.

So the following is the edited code for your particular situation:

 private Vector3 previousPosition;
 public float curSpeed;
 void Update()
     Vector3 curMove = transform.position - previousPosition;
     curSpeed = curMove.magnitude / Time.deltaTime;
     previousPosition = transform.position;

    if(distance < Range)//if he is in range to attack
       SetBool("attack", true); //go to the attack state
    else{//if not in range
      SetBool("attack", false);//leave attack state
      SetFloat("speed", curSpeed);//go to idle or walk according to your movement speed

So In the Animator Controller you should have 3 states EX: Idle, Attack, Walk

----------Idle State--------------

Idle goes to Walk State if “attack”==false && “speed” > 0.1f

Idle goes to Attack State if “attack” == true

---------Walk State--------------

Walk goes to Attack State if “attack” == true

Walk goes to idle if “attack”==false && speed < 0.1f

--------Attack State-------------

Attack goes to Idle State if “attack” == false && speed < 0.1f

Attack Goes to Walk State if “attack”== false && speed > 0.1f

The above code is untested but since it was an accepted answer I assume that it should work for your needs. However the part where your dividing by Time.deltaTime does seem a little sketchy to me. I would probably remove it but hey, if it works, it works.