- Home /
how to have animator play sprite animation on button press. wait for completion.
. So my set up is i have various animations for character movements. i have a animator controller set up to play them depending on the value of a variable. i then have code where when a button is pressed, depending, variable mvar is changed.
. Im trying to get my character to jump now. So I tried to code it to where the when the space key is pressed, it changes the mvar value. Which tells the animator controller to play the jump animation. Then I wait a couple seconds and change the value back to 0 telling the controller to play the standing animation. I cant get thing to work. I dont know how I would get this to work. Please Point me in the right direction. Everything I see is for 3d animations and this is 2d... . The debug messages works. it waits. but the jump animation flashes for split second before returning to standing animation. Ive messed with wait times up to 8 seconds with no luck. I think I am not using appropriate code. How to write it to wait for the animations completion?
heres my code:
public class FSpriteCntrl : MonoBehaviour {
private Animator animator;
int keyw;
int keya;
int keys;
int keyd;
void Start () {
animator = this.GetComponent<Animator>();
}
void Update () {
//sets values if any movemnt button is pressed
if (Input.GetKeyDown ("w")) {
keyw = 1;
animator.SetInteger ("MVar",1);
}
if (Input.GetKeyDown ("a")) {
keya = 1;
animator.SetInteger ("MVar",2);
}
if (Input.GetKeyDown ("s")) {
keys = 1;
animator.SetInteger ("MVar",3);
}
if (Input.GetKeyDown ("d")) {
keyd = 1;
animator.SetInteger ("MVar",2);
}
if (Input.GetKeyDown (KeyCode.Space)) {
StartCoroutine(Jump()); //when space key is pressed runs the subroutine.
}
//when wasd are let go sets the key variable to 0
if (Input.GetKeyUp ("w")) {
keyw = 0;
}
if (Input.GetKeyUp ("a")) {
keya = 0;
}
if (Input.GetKeyUp ("s")) {
keys = 0;
}
if (Input.GetKeyUp ("d")) {
keyd = 0;
}
//checks wasd if none are being held then sets variable to play stand animation
if (keyw == 0 && keya == 0 && keys == 0 && keyd == 0){
animator.SetInteger ("MVar", 0);
}
}
IEnumerator Jump() {
animator.SetInteger ("MVar", 5); //sets mvar to 5 telling animator controller to play the sprites jump animation.
Debug.Log("Before Waiting 1 seconds");
yield return new WaitForSeconds(1);
animator.SetInteger ("MVar", 0);//changes value back to zero so the character returns to standing animation.
Debug.Log("After Waiting 1 Seconds");
}
}
Your answer
Follow this Question
Related Questions
Dependency sprite animation from the variable 0 Answers
2D Sprite animation: Mesh swap or UV swap? 1 Answer
Sprite error while changing Animation clips 0 Answers
Wanting to have a sprite animation to only start playing once the player collides with it? 1 Answer
How do I check, and change, the current frame/time of a sprite animation in Unity 4.3? 0 Answers