How to lauch an animation from a script ?

Hello. I want my player to be able to punch when he uses the Mouse0 key but the animation doesn’t play and I don’t know why.
I’m using this script:

public class Punch : MonoBehaviour
{
private bool playerClicked;
Animation anim;

void Start ()
{
    anim = GetComponent<Animation>();
}
void Update ()
{
    Punching();	
}

void Punching()
{
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        playerClicked = true;
    }

    if(Input.GetKeyUp(KeyCode.Mouse0) && playerClicked == true)
    {
        anim.Play("Punch");
    }
}    

}

Hi !

You need to create an animator with a Punch trigger parameter. If you don’t know how to do that you can follow this tutorial, i learn so many things with it !

Once you do that, you have to call the trigger with something like that :

void Start ()
 {
     animator = GetComponent<Animator>();
 }
 void Update ()
 {
     Punching();    
 }
 void Punching()
 {
     if (Input.GetKeyDown(KeyCode.Mouse0))
     {
         playerClicked = true;
     }
     if(Input.GetKeyUp(KeyCode.Mouse0) && playerClicked == true)
     {
         animator.SetTrigger("Punch");
     }
 }   

And your player will play the Punch animation clip.

Hope it help.

Surely you want

GetMouseButtonDown

GetMouseButtonUp

OK thank you. I’ll try that later