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;
}
}