- Home /
Pause an animation with a button
I have animated my character upon button press to touch the floor.
I want to be able to pause the animation at any given time with either the same button or a different button. Here is the code for my button to play the animation.
public class Touch_floor_1 : MonoBehaviour {
Animator animator;
void Start () {
animator = GetComponent<Animator>();
}
public void Touch ()
{
animator.SetTrigger("Touch");
}
}
I have read a few articles on unity, specifically this one, yet I am unsure of how to go about doing this.
Answer by Addyarb · Apr 18, 2016 at 02:24 AM
Greetings,
The easiest way I can think of is to set animator.speed to zero.
If this doesn't work for you, please comment below and I'll give you a range of other solutions based on what you need!
Your app looks awesome, keep up the good work. Good luck!
EDIT:
Here is a piece of code that (hopefully, I haven't tested yet!) sets the current state's animation speed to zero. It does this by getting ALL of the Animator's states, iterating (in Layman's terms, go through each of them) through them, and then seeing if one has the same name as the one that is currently active. If it does indeed have the same name, it references it and then sets it's speed to zero.
You can use this same method to un-pause it (just set the speed to 1).
Why is this better or different than just setting Animator.speed to zero? Well, you may have multiple layers in your Animator, and settings the entire Animator's speed to zero may cause some issues.
Anyhow, here's the code!:
foreach(AnimationState state in anim)
{
if(anim.GetCurrentAnimatorStateInfo().fullPathHash == state.name)
{
state.speed = 0;
}
}
}
Thanks for the response!
I ended up using this code:
public Animation anim;
public void Pause() {
anim = GetComponent<Animation> ();
foreach (AnimationState state in anim) {
state.speed = 0F;
When I use the one you provided, I receive an error that "Animator" does not contain a definition for "GetCurrentAnimatorStateInfo" and no extension method "GetCurrentAnimatorStateInfo" of type `Animator' could be found. I am missing a using directive or an assembly reference, but I am not sure what.
$$anonymous$$aybe not the classiest, but worked like a charm! Thanks!
Always remember to set it to 1 again when you need the animation to play again.
Thanks!
Your answer
Follow this Question
Related Questions
What's a good book to learn scripts for Unity? 1 Answer
Pausing an animation 3 Answers