- Home /
(C#) Switching back and forth between an "idle" animation and a "punch" animation
I always wanted to experiment with custom characters and animations, but making 3D models is kinda complicated, specially animated and rigged ones so I experimented with a poorly drawn 2D character.
I made myself a nice spritesheet (Here it is) with 4 animations of 4 frames each. I experimented all morning with it and managed to make an animator with all of the animations, and a parameter: "animState", an integer that decides which anim is playing.
For now I'll just focus on the "spuder_idle" and "spuder_punch" states. When the "animState" parameter equals 1, it will transition from "spuder_idle" to "spuder_punch" animation.
Now look at this piece of code:
void Update () {
if (Input.GetKeyDown (KeyCode.Mouse0)) {
//punch state
anim.SetInteger("animState", 1);
//wait for the end of the animation and then anim.SetInteger("animState", 0);
}
What happens with this script is that at the start of the scene, my character is playing the idle animation. When I press the left mouse button it starts playing the punch animation forever.
I know why this happens: It happens because the "punch" state ends after the animation has played (ExitTime 1.0). But when it goes back to the "idle" state the animState parameter is still 1, so it goes back to the punch state instantly and so on.
To fix this I tried something like this:
if (Input.GetKeyDown (KeyCode.Mouse0)) {
//punch state
anim.SetInteger("animState", 1);
anim.SetInteger("animState", 0);
}
But it switches animState from 1 to 0 in the same frame. So nothing happens at all.
THE REAL QUESTION IS:
How do I wait for the animation to end and then, in that moment set animstate to 0? I found some "WaitForSomething" stuff in the documentation but I got no idea how to use them.
Or how do I setup my Animator in such a way that it's easier to switch states back and forth?
Answer by Baste · Feb 12, 2015 at 02:15 PM
You don't use SetInteger and an integer for this. Not only is it hard to read (you have to remember what int means what state), but you also run into the issue you're facing.
Use triggers instead. Create a trigger called "punch" in the animator, and have the animator transition from idle to punch on that trigger. Then you call:
anim.SetTrigger("Punch");
This will have your animator transition to the punch state, and then return to idle until the button is pressed again.
Triggers are what you want to use for single-fire events in the animator. Bools, ints and float are something you'll want to use for persistent states - such as having your character be crouched or not, or selecting what weapon (if any) your character model should be holding.
Thanks a lot. I didn't know what "trigger" type did. I'm mostly familiar with normal variable, not unity ones.
I thought it would be like a boolean but now I tried it and it resets automatically. Thanks.