- Home /
how can I make an animation play on keypress but stop on release?
I have a model with an animator component and an animation controller. I want the animation to only play when I press right and left arrow keys. I have gotten it to play the animation but if I release the button it just keeps on playing. I've tried lots but it just wont stop.
Here's my script:
#pragma strict
var speed = 5.0;
function Start () {
}
function Update ()
{
if (Input.GetAxis("Horizontal") > 0) {
transform.Translate(0, 0, 5 * Time.deltaTime);
transform.eulerAngles = new Vector3(0,0,0);
animation.Stop ("walk");
}
if (Input.GetAxis("Horizontal") < 0) {
transform.Translate(0, 0, 5 * Time.deltaTime);
transform.eulerAngles = new Vector3(0,180,0);
animation.Stop ("walk");
}
if (Input.GetAxis("Horizontal") == 0){
animation.Stop("walk");
}
}
Any suggestions extremely welcome!
Answer by Xtro · Aug 14, 2013 at 02:10 PM
First of all, There are two types of animation system in Unity. First and old one is called Legacy Animation and the other is Mecanim.
Legacy animation system is driven by "Animation" component and the animation files are attached to that component directly. The component you see here... http://docs.unity3d.com/Documentation/Components/class-Animation.html
Mecanim is the new and the good animation system. It's complex to understand at first but has very big advantages. It's driven by "Animator" component (notice the name is different) and the "Animator Controller" file. The animation files are attached to Animation Controller in a state machine format.
As I see from your code, you are using Legacy system. So, you should be using Animator and Animation Controller. Just remove them from your game object.
the "animation" object in the gameobject is used for legacy system. You can easily start and stop the animations which are registered on the animation component just like in the web page I linked above.
Notice : To be used in legacy system, models and animation files must be imported as "legacy" mode in the "Rig" tab of model importer window.
Answer by theUndeadEmo · Aug 14, 2013 at 02:11 PM
simple solution if you haven't tried this is to set the animation to loop or not
inside you if statements for when key pressed
animation["animationClipName"].wrapMode = WrapMode.Loop;
at start of your function Update()
have
animation["animationClipName"].wrapMode = WrapMode.Once;
see if that solves it, but when you have lots of aniamtions you may have to search a better solution.
this will work if you are using Legacy animation type i believe
Your answer
Follow this Question
Related Questions
How to get my rigged character to simply walk from A to B (Cinematic not game) 1 Answer
What's the difference between animation and animator ? 0 Answers
C# Movement Script 0 Answers
Mixamo + Animation Movement BASIC 2 Answers
Animation clips anyone? 1 Answer