How to play an AnimationClip when key is pressed in Unity3d, C#?

By the looks of your code you’re never actually referencing the attached Animaton on your component. Try assigning anim it’s component in the Start method, like this:

public class PlayAnimation : MonoBehaviour 
{

    public AnimationClip walk;
    Animation anim;
 
    void Start() 
    {
        anim = GetComponent<Animation>();
    }
     
    void Update () 
    {
        if (Input.GetKeyDown(KeyCode.W)) 
        {
            anim.clip = walk;
            anim.Play();        
        }
    }
}

Leave a Comment