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

More efficient double keypress function

Discussion in 'Scripting' started by GFFG, Jul 12, 2016.

  1. GFFG

    GFFG

    Joined:
    Nov 13, 2014
    Posts:
    224
    Hey,

    I've made the following code to be able to activate thrusters on my spaceship everytime I press K and when I release the key the thrusters stop. It works but it's not that reliable. Sometimes the thrusters stay on even though I released the key and sometimes they don't engage depending on how quickly I press K.

    Does anybody know of a more reliable what to do this that works every time regardless of how quickly I press and relate a key? hers the code:
    Code (CSharp):
    1.  
    2. void ControlThrottle()
    3.  {
    4.  
    5. if (Input.GetKeyDown(KeyCode.K))
    6.         {
    7.             BottomThrust.active = true;
    8.  
    9.  
    10.  
    11.         }
    12.         else if (Input.GetKeyUp(KeyCode.K)){
    13.             BottomThrust.active = false;
    14.  
    15.     }
    16.  
    17. }
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    I would certainly remove the else, maybe that helps
    Another problem could be the way you call this method, e.g. input should go into Update, not fixedUpdate, or it should be in a method that's called in the update

    You could also do something like this instead of GetKeyUp and GetKeyDown:
    Code (CSharp):
    1. BottomThrust.active = Input.GetKey(KeyCode.K);
    Which would activate your thrusters if you are pressing the button and deactivate them if you don't
     
  3. GFFG

    GFFG

    Joined:
    Nov 13, 2014
    Posts:
    224
    Wonderful! Thank you for the advice and actually the code line you wrote works like a charm. It works every time with no issues. I didn't know you could write it that way but it's definitely more efficient. Thanks :)