- Home /
Play animation only when a key is being held down
Hi! Happy new year everyone.
I have a question, I want to animate a button being pressed, but needs to "reset" itself to its original state when the users let's go of the button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StrobeButton : MonoBehaviour
{
public Animator knop;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
knop.Play("StrobeUp");
}
else if (Input.GetKey(KeyCode.Space))
{
knop.Play("StrobeDown");
}
}
}
That is what I have so far, but doesn't seem to work, still learning ofcourse. Maybe there is someone who can fix this for me?
Thanks!
Answer by Pokedlg3 · Jan 04, 2021 at 09:05 PM
First you will have to create a parameter, it can be of the bool type:
Then create a State, with the name Transition, in Create State> Empty
Then place your animation and create two transitions, round trip, look:
On the outward transition, deselect Has Exit Time and click on the "+" to add the parameter, leave it as true.
In the transition back, do the same thing but leave the parameter false.
Then replace your script with this one
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StrobeButton : MonoBehaviour
{
public Animator knop;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
knop.SetBool("Bool", true);
}
if(Input.GetKey(KeyCode.Space))
{
knop.SetBool("Bool", true);
}
if(Input.GetKeyUp(KeyCode.Space))
{
knop.SetBool("Bool", false);
}
}
}
Answer by Llama_w_2Ls · Jan 04, 2021 at 08:34 PM
You can use tracker bools to keep track of whether space is still being held and whether the animation is currently playing. For example:
private bool AnimationIsPlaying;
private bool SpaceIsHeld;
void PlayAnimationOnKeyHeld()
{
if (Input.GetKey(KeyCode.Space))
{
SpaceIsHeld = true;
}
else if (Input.GetKeyUp(KeyCode.Space))
{
SpaceIsHeld = false;
}
if (SpaceIsHeld)
{
// if animation isn't already playing
if (!AnimationIsPlaying)
{
knop.Play("StrobeDown");
AnimationIsPlaying = true;
}
}
else
{
// Stop playing animation
}
}
Running the method in the Update should ensure that the animation only is played while space is held, and when let go, the animation should stop playing. @vershurengiovanni
Your answer
Follow this Question
Related Questions
IEnumerator Loop on keypress 1 Answer
Trying to find the highest number than add it to itself. 2 Answers
Move from A to B after recieving touch input 1 Answer
Need help fixing my script 1 Answer
Slowly increase motor.force 1 Answer