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){

Any suggestions extremely welcome!

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… Unity - Manual: Animation

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.

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()


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