I’m making a melee script in unity that plays an animation when V is pressed but it does not work (no errors).
I don’t know what I’m doing wrong.
I have the animation inside of an animator.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Punch : MonoBehaviour
{ public Animation PunchAnim;
// Start is called before the first frame update
void Start()
{
//PunchAnim = GetComponent<Animation>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.V)){
Debug.Log("Player Punching");
PunchAnim.Play();
}
}
}
In order to play an animation you need an Animator as @DizeLuido mentioned.
Once you attach the Animator game component to your game object and you added the Animation clip to in the Animator window (in the one screenshot I have 3 clips), you can simply call which animation you want to play.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Punch : MonoBehaviour
{ public Animator animator;
public const string PLAYER_PUNCH = "punchAnim"; // the name of your animation clip
// Start is called before the first frame update
void Start()
{
animator= GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.V)){
Debug.Log("Player Punching");
animator.Play(PLAYER_PUNCH ); // plays player punch animation
}
}
}
Just make sure that you if you don’t want the animation to constantly loop that you click on the animation clip in the asset follow and UNCHECK the LOOP TIME checkbox (see images in link).
Site won’t let me upload images so here are screenshots of how I’m currently doing it.
Ever since I had more complicated animations, I’ve been following this tutorial.