I have a simple state machine as shown below

Idle → Kick is simply triggered when player hits the B key. I’ve set Kick → Idle with exit time 1 so that Kick gets played once and then automatically returns to the Idle state. This is the Kick → Idle properties.
The thing is, Kick plays twice for some reason. I took a close look and found that Kick played once, then it returned to Idle for like 1 frame and then again returned to Kick to play the second time and then finally returned to Idle. I don’t know if this is a bug or some mistake on my side.
This is the code to trigger Kick.
if(Input.GetKey(KeyCode.B))
{
anim.SetTrigger("kick");
}
Input.GetKey(KeyCode.B) will return true while the user hold the key down.
A trigger is consumed(value is to false) as soon as a transition use the trigger.
So if on the first frame you set your trigger to true, the statemahcine will start the transition to kick, if on the next Update you still have the key pressed it will set the trigger back to true, hence playing the kick animation twice.
In this case maybe you should use Input.GetKeyDown which will return true only on the frame that the user did press the key.
11 Likes
I changed it to GetKeyDown and it worked! Thanks!
Thanks. That was helpful !
Why would you necro a 6 year old thread just to say that?
same problem but in mobile game
forget the trigger system and work with the animator.Play(“animationClipName”);
It works a lot better.
in my case I used the play command like this:
if (animator.GetBool("Running"))
{
animator.Play("Jump(Run)");
}
else
{
animator.Play("JumpVertical");
}
animator.SetBool("IsJumping", true);
}
Sure, GetKeyDown solves this, but I want GetKey, else my mouse would be dead in a second with all those clicks.
Edit: figured it out:
Add this:
if (Input.GetKeyUp(KeyCode.Mouse0))
{
anim.ResetTrigger("TriggerName");
}