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.