- Home /
 
Fix animation to AI through script
How do I add animations to my ai through script, When it's detected me it will start a walk animation and when I'm not detected it should play an idle animation. How do I add this? (Sorry for bad knowledge)
 var target : Transform; //the enemy's target
 var moveSpeed = 3; //move speed
 var rotationSpeed = 3; //speed of turning
 var range : float=10f;
 var range2 : float=10f;
 var stop : float=0;
 var myTransform : Transform; //current transform data of this enemy
 function Awake()
 {
     myTransform = transform; //cache transform data for easy access/preformance
 }
  
 function Start()
 {
      target = GameObject.FindWithTag("Player").transform; //target the player
  
 }
  
 function Update () {
     //rotate to look at the player
     var distance = Vector3.Distance(myTransform.position, target.position);
     if (distance<=range2 &&  distance>=range){
     myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
     Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     }
  
  
     else if(distance<=range && distance>stop){
  
     //move towards the player
     myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
     Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
     }
     else if (distance<=stop) {
     myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
     Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
     }
  
  
 }
 
              [edit] I have made the animations, I just need some help with the script
Answer by wijesijp · May 30, 2014 at 09:17 AM
First create a reference to your Animator,
 public Animator anim;
 
               Then to play the animation at correct place, say for walking (if your walk animation name is walk)
 anim.Play("walk");
 
               Check the following tutorial to do more with unity mecanim animation
Your answer
 
             Follow this Question
Related Questions
Enemy AI Animation 0 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
my AI(soldier) follow me but without animation ? 0 Answers
Play specific animation in mechanim 1 Answer
Custom Boss Character AI 0 Answers