How can you stop an animation when not pressing a key?

So I made a walking animation and I looped it, but when played it, the animation kept going without me pressing a key. I used this script below:

function Update (){

if(Input.GetKey(KeyCode.W)){

      animation.CrossFade("DefaultAnim", 0.2); 

}

else{

animation.CrossFade(“Idle”);

}
}

And it still keeps doing it. Any suggestions?

You should use GetKeyDown and GetKeyUp, it is true only for one frame. In your example, you will launch the crossfade at every frame since the player hit the “W” key.

Try :

function Update (){

    if(Input.GetKeyDown(KeyCode.W)){

        animation.CrossFade("DefaultAnim", 0.2); 
    }

    if(Input.GetKeyUp(KeyCode.W)){

        animation.CrossFade("Idle");

    }
}