- Home /
Enemy to follow player after animation completes
Hello all,I'm a newbie to Unity. So please help me with this.
My 2D game object(zombie) needs to start functioning only when the player is at a specific distance. The functioning is as follows: The game object must animate first and then only follow the player continuously after. It must face the player at all times and not stop functioning even if he leaves its vicinity.
I wrote the following piece of code which won't work.
public class ZombieFollow : MonoBehaviour
{
private Animator zAnim;
public Transform target;
void Start()
{
zAnim = GetComponent < Animator > ();
}
void Update()
{
//[WORKING]Animates when the player is close
if (Vector3.Distance(transform.position, target.position) < 3f)
{
zAnim.SetTrigger("appear");
zAnim.SetTrigger("walk");
}
//[NEED CODE]must wait first for the animation to complete
transform.lookAt(target);//[NOT WORKING]Makes the zombie invisible
//[NEED CODE]Follow the player and attack if collided
}
private void OnCollisionEnter2D(Collision other)
{
if(other.gameObject.tag=="Player")
{
zAnim.SetTrigger("attack");
//[NEED CODE]wait again for animation to complete
Destroy(other.gameObject);
}
}
}
Answer by smallbit · Jun 20, 2016 at 04:46 AM
You need to divide the code for appear and walk into two methods. Than you have two options, 1) in your animation (FBX file) add an event in the end of animation, and call the second method from this event (note: if you add event late in the clip and you use transitions it might get skipped). 2) use ANIMATION STATE MACHINE to do same as above but in more controlled way.
Your answer
Follow this Question
Related Questions
Good Game by One Person, Is it Possible? 2 Answers
Why aren't my parameters for animation not working? 0 Answers
What would be the best way to do something based on the animation state of the character? 0 Answers
2d game for my first unity project. 1 Answer
How to edit an animation in unity animation system by using script? 0 Answers