Search Unity

Animate object on button down, reverse animation on button up

Discussion in 'Scripting' started by Proto-G, Oct 15, 2019.

  1. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    213
    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.

    Code (CSharp):
    1. if (Input.GetButton("button"))
    2. {
    3. Menu = true;
    4. if (Menu==true)
    5. {
    6. animation.CrossFade("Menu");
    7. animation.Play();
    8. }
    9. else if (Menu==false)
    10. {
    11. animation.CrossFade("Menu");
    12. animation.Play();
    13. }
     
    Last edited: Oct 15, 2019
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    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:
    Code (csharp):
    1. public Animator animator; //assign in inspector or with GetComponent
    2. ...
    3. bool openMenu = Input.GetButton("button");
    4. animator.SetBool("MenuOpen", openMenu);
    I'd recommend StateMachineBehaviour to do this.
     
    Proto-G likes this.
  3. JesusMartinPeregrina

    JesusMartinPeregrina

    Joined:
    Nov 2, 2013
    Posts:
    44
    Well, before trying a new system I would try to fix your code.
    This will never be executed:
    Code (CSharp):
    1.  
    2. else if (Menu==false)
    3. {
    4.    animation.CrossFade("Menu");
    5.    animation.Play();
    6. }
    7.  
    cause you set menu to true just before the if...
     
    Proto-G likes this.
  4. Proto-G

    Proto-G

    Joined:
    Nov 22, 2014
    Posts:
    213
    Thank you for this solution.