Search Unity

Simple animation in Javascript.

Discussion in 'Scripting' started by JonasSilverio, Jan 12, 2014.

  1. JonasSilverio

    JonasSilverio

    Joined:
    Jan 12, 2014
    Posts:
    5
    Hey, i made a simple script and what i want him to do is:

    - When i press "M" a menu (retangle/gameObject) has to go up, by performing an animation.
    -If he is already up, when i press "M", he has to go Down, with an animation as well.

    Here is the code:

    -----------------------------------------------
    #pragma strict

    var menuTurn : boolean;

    function Start () {
    menuTurn = false;

    }

    function Update () {


    if (Input.GetKey ("m"))
    {
    if (menuTurn == false)
    {
    animation.Play ("turningOn");
    }

    if (menuTurn == true)
    {
    animation.Play ("turningOff");
    }
    menuTurn = !menuTurn;
    }

    }

    --------------------------------------------------

    When i press play, and then "M" the animation happens, the object goes up, and menuturn is changed to true.
    i press the second time, the object goes down and menuturn turns false.
    but if i press a third time, the object teleport up, and go down again, with the animation "turningOff", and the menuTurn boolean keeps false.
    and if i press again and again it will do the error, then the right thing, then the error again, repeteadely and randomly. =p

    What am i doing wrong?
     
    Last edited: Jan 12, 2014
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Please use code tags.
    I'm not sure why it happens as you say, but perhaps it's because Input.GetKey fires every frame, switching menuTurn every frame it's held and reversing the animation, try using GetKeyDown instead.
    I would also add an else statement to the logic:
    Code (csharp):
    1.  
    2. else if (menuTurn == true)
    3.  
     
  3. JonasSilverio

    JonasSilverio

    Joined:
    Jan 12, 2014
    Posts:
    5
    YAAY.

    Thanks a lot, the GetKeyDown worked.
    Sorry about the code tags, this is my first question here.
    I will use else too, thanks for the tip.