Play Animation on GetKeyDown (Beginner)

Hello Guys,

I have recently started to learn coding in Unity using udemy and I am curious to experiment on my own and start exploring unity. Iā€™d like to ask a very basic question: I want to play an animation once I press ā€˜Sā€™ key on my keyboard. Below is my code:

void Update(){
	if(Input.GetKeyDown("e")){
		animation.Play("cube");
		}
	}

There is an error in Mono, attached is the image:

86348-screen-shot-2017-01-21-at-005153.png

Thank you :slight_smile:
Waqas

Judging by the error, you are getting the animation without telling Unity to give you the correct type.

GetComponent(Animation) will give you the component without casting it to an Animation type, if you want to get the correct type, you should use GetComponent()

Try the following:

// Important to get the animation component as an animation type.
animation = GetComponent<Animation>();

void Update(){
	if(Input.GetKeyDown("e")){
		animation.Play("cube");
	}
}