- Home /
Play Animation while Button is pressed
Hi I implemented a 3D Char into my Unity project and finally managed to get the animations playing, however the run animation just play once as soon as I press the forward button. What I want is that as long as the forward Button is being pressed the animation should play and not just once.
Can someone help me with this ?!
var walking = false;
function Update () {
if (Input.GetAxis("Horizontal") > 0.2 && !walking) {
animation.CrossFade ("walk");
walking = true;
}
if (Input.GetAxis("Horizontal") <= 0.2 && walking) {
animation.CrossFade ("idle");
walking = false;
}
Answer by FLASHDENMARK · Jan 27, 2012 at 09:22 PM
Why not do it much simpler?
function Update () {
if(Mathf.Abs(Input.GetAxis("Horizontal")) > 0.2)
animation.CrossFade("walk");
else
animation.CrossFade("idle");
}
This will make the animation play until the player has stopped walking.
Mathf.Abs returns the absolute value of a float. If you don't want that you can just remove the "Mathf.Abs" part.
well that might make my script easier I don't know :-) If so thank you but the animation is still being played just once if i keep the forward button pressed.
What about?:
if(Input.GetAxis("Horizontal") || Input.GetAxis("Vertical")){
animation.CrossFade("walk");
}else
animation.CrossFade("idle");
That is used in one of my old projects and plays the walk animation repeatedly when the w,a,s or d key is pressed and returns to idle when no button is pressed.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063457im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Go Idle after Animation 0 Answers
I HAVE 3 QUESTIONS.. 0 Answers
Reverse animation c# does not work. 0 Answers
Can Unity 2017.3 change image of animation clip so just needed 1 animator? 0 Answers
Sword Animation 1 Answer