Animate object on button down, reverse animation on button up

Hello. I’m a novice at coding so…

I’m trying to add an animated object to the players arm that will animate open on button press down and animate closed on button release. I’d also like UI to appear once the animate open completes (maybe with a delay?). Can someone please assist me with the proper C#? And maybe point me in the right direction with the UI? Thanks.

if (Input.GetButton("button"))
{
Menu = true;
if (Menu==true)
{
animation.CrossFade("Menu");
animation.Play();
}
else if (Menu==false)
{
animation.CrossFade("Menu");
animation.Play();
}

It looks like you’re using the legacy animation system (using the component “Animation”). The new animation system Mecanim (using the component “Animator”) makes this sort of thing much easier (you’ll just call SetBool with true or false), and I recommend you check out a tutorial on that system. Your code would end up looking something like:

public Animator animator; //assign in inspector or with GetComponent
...
bool openMenu = Input.GetButton("button");
animator.SetBool("MenuOpen", openMenu);

I’d recommend StateMachineBehaviour to do this.

1 Like

Well, before trying a new system I would try to fix your code.
This will never be executed:

else if (Menu==false)
{
   animation.CrossFade("Menu");
   animation.Play();
}

cause you set menu to true just before the if…

1 Like

Thank you for this solution.