Trigger animation

Hi,
I am new to unity programming .I have following issue

             -We want enemy object to Play certain animation if it enter trigger of player .
             -Player trigger is detected with debug.Log but the object animation is not .it   keeps playing animation given in update.Thanks in advance

          using UnityEngine;

using System.Collections;

public class test : MonoBehaviour {

// Update is called once per frame
void Update () {

	GetComponent<Animation>().Play ("Turn");

}
public void OnTriggerEnter(Collider other)
{
	if (other.gameObject.tag == "Player") 
	{

	    GetComponent<Animation>().Stop ("Turn");
		Debug.Log("Trigger");
	}
}

}

Update is called on every frame, so I think when you’re calling the new animation, its just immediately being overwritten by the update.

It might be a quick and easy fix to add a bool, which returns true when the player hits the trigger, and goes back to false when the animation is finished. Then use an if statement in your update to check that the bool is true.

If you have a lot of animations though it might be worth making a State Machine, which can be used to switch animations but its more complicated.

Untested example:

private bool playTriggerAnimation;               //create a boolean

    void Update () {
     if(!playTriggerAnimation)                 //if the boolean is false (the ! prefix is a shorthand way of saying "PlayTriggerAnimation == false"
         GetComponent<Animation>().Play ("Turn");
     
     }
     public void OnTriggerEnter(Collider other)
     {
         if (other.gameObject.tag == "Player") 
         {     
             playTriggerAnimation = true;
             GetComponent<Animation>().Stop ("Turn");
             Debug.Log("Trigger");
             GetComponent<Animation>().Play ("NewAnimationHere");

             if(!GetComponent<Animation>().isPlaying("NewAnimationHere")) //if "NewAnimationHere" is not playing
                playTriggerAnimation = false;
         }
     }

If you do want to create a state machine to handle multiple animations, theres a great tutorial for it here http://www.3dbuzz.com/training/view/3rd-person-character-system/integrating-maya-characters - starting at no.15 :slight_smile:

Hi!
if you are using collision this might be the good one!

animator anim;

bool hitplayer;

void Update(){

if(hitplayer){

anim.play(“you animation for hitplayer like fight when hit the player”);
}
}

void OnTriggerEnter2D(Collider2D other){
hitPlayer = false;
anim.Play (“fightAnim”);

}
}

void OnTriggerExit2D(Collider2D enemwalk){

hitPlayer = true;

}
its works great with my game!. Hope this help :slight_smile: