- Home /
Help with an animation script.
function Update()
{
if(Input.GetKeyDown("w"))
{
animation.Play("Animwalk", PlayMode.StopAll);
}
}
I am creating a game. I used some simple code to create this but now, when I test it and push "w" the animation continues to play without end. I am not the best coder and am still green around the ears. If someone finds a solution(s) then please post the code in the comments section.
Answer by syclamoth · Sep 19, 2013 at 04:21 AM
Let me explain exactly what this code snippet does.
Every frame it checks for whether the 'w' key was first pressed that frame. That is to say, Input.GetKeyDown will only evaluate 'true' once per key-press, and only at the very beginning.
When the key gets pressed, it tells the animation component to start playing an animation. Keep in mind that this is an instantaneous command, that changes the state of the animation- the animatior component itself will happily continue playing the animation until it is finished or, depending on the looping mode, forever. The 'StopAll' command makes sure that there will only be one animation playing at a time.
Currently, your code is doing exactly what you told it to do. What is the actual intended behaviour? You could simple add a matching 'Input.GetKeyUp' command, with 'animation.Stop()' to force the animation to end at the end of the keypress, if that's what you were after.
So you mean i should add this?
else (Input.Get$$anonymous$$eyUp ("w"))
{
animation.Stop ("Animwalk", Play$$anonymous$$ode.StopAll);
}
Almost. As you can see from the script reference, there is no valid overload for Stop that takes those parameters- in your case, you can simply use 'animation.Stop()' and it will work just fine.
Also, you don't need the 'else' statement there. While it is very rare to have a key-down and a key-up in the same frame, you don't want to create an edge-case bug by accident (the else statement would prevent the animation from stopping immediately- you'd need to press the key again!).
Your answer
![](https://koobas.hobune.stream/wayback/20220613114439im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Animation stoping!! 1 Answer
Where is the problem? 0 Answers