Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Need help with OnTriggerStay() and GetKeyDown()

Discussion in 'Scripting' started by AfrogDev, Sep 13, 2013.

  1. AfrogDev

    AfrogDev

    Joined:
    Nov 26, 2012
    Posts:
    2
    I have a javascript with a .GetKeyDown() function inside OnTriggerStay(), the purpose of which is to execute a block of code when the "E" key is pressed while the trigger is active. It works fine, only most of the time, the code is executed four times. I have NO idea why this could be. I used Debug.Log and sometimes when the code is executed it is logged four times and sometimes only once.

    Code (csharp):
    1. function OnTriggerStay() {
    2.  if(Input.GetKeyDown(KeyCode.E)) {
    3.   Debug.Log("KEY PRESSED");
    4.  }
    5. }
    This is an outline of the code and KEY PRESSED is often logged four times. :confused:
     
    OfficalUntitledGames likes this.
  2. cjow

    cjow

    Joined:
    Feb 29, 2012
    Posts:
    132
    Check for Input in Update instead and use OnTriggerStay to toggle a bool saying if it should be checking for Input or not.
     
    OfficalUntitledGames likes this.
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    OnTriggerStay is run like FixedUpdate (since it involves physics), so none of the *Down or *Up events will work correctly inside it for the same reason that they won't work right in FixedUpdate. All *Down and *Up functions must only be used in Update, or coroutines that run every frame.

    --Eric
     
  4. vexe

    vexe

    Joined:
    May 18, 2013
    Posts:
    644
    What is the reason that they don't work correctly? - Could you elaborate a bit more? - Thanks.
     
  5. ludumez

    ludumez

    Joined:
    Jul 20, 2014
    Posts:
    1
    This is a incredibly late response but just in case anyone was having the same issue.
    Fixed update doesnt run every frame like Update it runs a fixed amount of time per second, so if you are looking for an input during fixed update and the fixed update isn't ocurring at the same time as the input key down it wont detect the input since it isn't ocurring at the same time.
     
    ntkog likes this.
  6. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,646
    Just to clarify,
    FixedUpdate()
    runs every Physics update, while
    Update()
    runs every frame.
    Input.GetKeyDown()
    only returns true the exact
    Update()
    frame that it is pressed, and since they're not perfectly in sync, sometimes when you press the key it won't register, or will register multiple times.
    Input.GetKey()
    should still work as expected though, since it returns true the entire time the key is pressed down (although, is used for different purposes).
     
    ntkog and Ethan_John like this.