How to play animation (C#)

I created an animation and animator components and putted the animation on the parameters and changed the animation to legacy and I wrote this…

if (Input.GetKey (KeyCode.W))
    GameObject.Find("Object").GetComponent<Animation>().Play("AnimtionName");

but it didn’t work… I need help in this
Any help would be useful, Thanks in advance

You should use the animator,wich is automatically created when you make an animation for a gameobject. Then in your script you’ll write

 if (Input.GetKey (KeyCode.W))
     GameObject.Find("Object").GetComponent<Animator>.SetTrigger("PlayAnimation");

Watch this tutorial about the animator for more infos. Hope it helped :wink:

For play an animation first you should make an animator controller and then you can paly animation by script

animator anim;
if (Input.GetKey(keycode.A)
anim.setbool (“name of the animator state” , true )

note that 1st parameter is for name of state and 2nd one is for bool value.

Hey @Ihabbalakho I would love to help! Okay so the issue with what you are doing is that you are attempting to directly modify the component. Unity doesn’t like this and requires you to make a reference of the component first as a variable, and then play the animation from that variable.

Example:

var gameObjectAnim = GameObject.Find("Object").GetComponent<Animation>(); gameObjectAnim.Play("AnimationName");

I hope this helped! If you have any other questions I would be glad to help!