- Home /
Play anaimation when key pressed
Hello! I am wanting my cube to play an animation when W is pressed, but when I code it, "animation" is invalid. Here is the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Player : MonoBehaviour {
public GameObject player;
private Animator forwardAnimation;
// Use this for initialization
void Start () {
forwardAnimation = player.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.W)) {
transform.position += new Vector3(1,0,0);
forwardAnimation.animation.Play("forwardAnimation");
}
}
} The line in update that starts with "forwardAnimation", I type in anaimation.Play but it is invalid. Is there any other way to do this code? If so please say so below. Also on my game object I have an animation attached with the forward animation on it if that helps. Thanks.
Comment
Answer by abhaychandna · Dec 16, 2017 at 03:56 PM
You can try this
public Animation anim;
Start()
{
anim = GetComponent<Animation>();
anim.Play(anim.clip.name);
}
if that doesn't work maybe this will help