Play Animation on Button press

Hi there!
I’m new to unity and have been having trouble getting my animation to play when I press the button. My script that I have use is

#pragma strict

function Update () {

  • if(Input.GetKeyDown(“w”))
  • {
  • GetComponent.().Play(“walk”);
  • }

Any help would be apprectiated.

Heya! If you’re new to Unity, you’re probably using the modern Unity animation system (Mecanim). This means that you have an Animator component on your object. This Animator component holds multiple animations and a state machine between them, so that you can do things like tell Unity to transition from Idle to Walk to Run animations.

There’s an excellent set of (short) video tutorials on the topic here: Controlling Animation - Unity Learn

If you’ve already set up the Animator and the Triggers, but you’re just confused how to activate the animation, you’re probably looking for this snippet of code:

this.GetComponent<Animator>().SetTrigger("Walk");

Hey there, thanks for replying. I made a small script which I was hoping would work but when I attach it to the model it says it can’t find the animation file even though I attached that to the model too. My code is :

var Animation : String;
var w : KeyCode;

function Update()
{
if(Input.GetKey(w))
{
GetComponent.().CrossFade(Animation);
}

}