Animation looping question

In an FPS game I’m making, I set up an animation for gun-bob, and a script that enables the animation while walking forward (Holding ‘W’). I’ve tried setting the animation’s Wrap-Mode to Once or Loop.

If I set it to ‘Once’, the animation goes 1 loop and stops until I press ‘W’ again. (not what I want).

If I set Wrap-Mode to Loop, the animation loops infinitely even when releasing ‘W’. (also not what i want!)

Here’s my code:

using UnityEngine;
using System.Collections;

public class WalkingMovement : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
    if (Input.GetKeyDown (KeyCode.W)) {
            gameObject.GetComponent<Animation> ().Play ("WalkAnimation");
        }
    }
}

Also, if it’s useful, here is my animation in the Debug window…

2284969--153494--anim_debug.jpg

…Solved the problem. After setting Wrap-Mode to Loop. The solution was to use GetKey() and not GetKeyDown()

Also needed to add an Else-block and a Stop() call…

Working code…

using UnityEngine;
using System.Collections;

public class WalkingMovement : MonoBehaviour
{
    // Use this for initialization
    void Start ()
    {
    }
 
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKey (KeyCode.W)) {
            //gameObject.GetComponent<Animation> ().wrapMode = WrapMode.Loop;
            gameObject.GetComponent<Animation> ().Play ("WalkAnimation");
        } else {
            gameObject.GetComponent<Animation> ().Stop ("WalkAnimation");
        }
    }
}