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

OnTriggerStay2D with Input.GetButtonDown not behaving properly?

Discussion in 'Scripting' started by HaydarLion, Dec 21, 2016.

  1. HaydarLion

    HaydarLion

    Joined:
    Sep 17, 2014
    Posts:
    62
    Hey all,

    I have this following script in a game object:

    Code (CSharp):
    1.     void OnTriggerStay2D(Collider2D col){
    2.         if(Input.GetButtonDown("Action")){
    3.             Debug.Log("Got Key Press");
    4.         }
    5.     }
    But the issue is, it only registers the first click of the action button, and not every time you click while you are in that trigger. When I take the Debug.log line out and place it outside of this if statement, it is logged continuously until the object exits the trigger. How do I solve this?

    Thanks.
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    Input.GetButtonDown() will only return true for the 1 frame that the button first gets pressed. Physics functions, like OnTriggerStay2D(), do not occur every frame, but instead happen every time a certain amount of time passes (0.02 seconds by default). So it is possible that the physics functions do not get called for the 1 frame that Input.GetButtonDown() return true.

    I suggest setting a bool for "isColliding" that you set true/false when you enter/exit the trigger, then you can check Input.GetButtonDown() AND the "isColliding" bool in an update() function.
     
  3. HaydarLion

    HaydarLion

    Joined:
    Sep 17, 2014
    Posts:
    62
    That solved my problem thanks