- Home /
Animation on keyperss with animator
Hello! How can I play an animation on keypress? The animation is done, but I dont know how can I play the animation on keypress.
Answer by ParkerBennett · Aug 07, 2021 at 08:27 AM
The script below should do what you need.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Drop this onto the gameobject that has the animator component on it.
/// </summary>
public class PlayAnimationOnKeyPress : MonoBehaviour
{
// Declare a variable to hold your animator.
private Animator cubeAnimator;
// Start is called before the first frame update
void Start()
{
// Get the animator component of this game object.
cubeAnimator = this.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
// On every update, check to see if the key has been pressed.
if (Input.GetKeyDown(KeyCode.Space))
{
cubeAnimator.Play("MoveUp");
}
}
}
A few things to note though. 1. Make sure you drop this script on the Game Object that has the animator on it. 2. This is not a comprehensive solution, you will need to expand on it. (Such as controlling the states with various animations in the animator). This only demonstrates how to play the animation.
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
Damn, HOW CAN I KNOW, IF MY 2d ANIMATION SPRITE IS FINISHED??!! 0 Answers
Animation motion on base layer does not play after additional motion on second layer 0 Answers
Generic Animation Main Rig Doesn't Play Any Animation. 0 Answers
Is it possible to change a skybox material via (Animation)? 0 Answers