Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

GetButton too slow

Discussion in 'Scripting' started by cedart, Aug 19, 2015.

  1. cedart

    cedart

    Joined:
    Jul 10, 2014
    Posts:
    17
    Hello,

    I would like to do a simple thing, but I can't.
    I want when the player push a button, he take an object. And when he push the same button, he put down the object.

    Code (JavaScript):
    1.     if(Input.GetButtonDown("Fire3") && haveObject == false){
    2.         haveObject = true;
    3.     }
    4.     if(Input.GetButtonDown("Fire3") && haveObject == true){
    5.         haveObject = false;
    6.     }
    7.     if(haveObject == true){
    8.         portableObject.transform.position = transform.position;
    9.     }
    But when I push the button, he take the object and put it immediatly.
    I think that's because the button is still pushed for the second condition.

    Someone have a solution pleaase ? :)

    Thanks in advance !

    Cédric (french man who don't speak english good :) )
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,848
    Mai oui! The value of Input.GetButtonDown() is not going to change between one line and the next. In fact, it will only change on the next frame.

    Try this.

    Code (JavaScript):
    1.     if (Input.GetButtonDown("Fire3")) {
    2.         haveObject = !haveObject;
    3.     }
    4.     if (haveObject){
    5.         portableObject.transform.position = transform.position;
    6.     }
     
  3. cedart

    cedart

    Joined:
    Jul 10, 2014
    Posts:
    17
    Nice idea thanks. Yes I'm not yet used to thinking with frames :)
    So finally i can just write an else if instead of the second if.

    Thank you so much :)
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Whenever you face an issue like this, you should work through your code line and by line and analyze the logic.

    - if a button is down and have object is false, set have object to true
    - if a button is down and have object is true, set have object to false
    - if have object is true, move the object

    The error in logic should jump right out at you.
     
  5. cedart

    cedart

    Joined:
    Jul 10, 2014
    Posts:
    17
    Yeh, but I use most often line by line compilation, like a "normal" program :)
    In the update function, it's a little bit different and I've to get used to :)