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!

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

First you will have to create a parameter, it can be of the bool type:

173587-parbool.png

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.

alt text

In the transition back, do the same thing but leave the parameter false.
alt text

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);
    }
 }
}