Input.GetKeyDown called 4 times

I have a class which has an OnTriggerStay2D method which works just fine. It looks something like this

void OnTriggerStay2D(Collider col) {
    if(col.gameObject.name == "Character") {
        if(Input.GetKeyDown(KeyCode.Z)) {
            times ++ ;
            print("Called :" + times) ;
        } 
    }
}

where times is private int times = 0. In the console I get the result:

 Called : 1
 Called : 2
 Called : 3
 Called : 4

I absolutely need it to be called only one time at best or an odd number of times at least and I don’t even know why does it get called 4 times.

Best regards!

You should use the Input in the Update function. I think your void OnTriggerStay2D(Collider col) is called 4 times per Update, even if you hit the key only one time. If you want to call the function only one time per frame you can work with booleans.

     if(col.gameObject.name == "Character" && !boolean) {
             boolean = true;
             times ++ ;
             print("Called :" + times) ;
     }

or something like that.

I’ve only been using Unity for half a year so don’t except this answer to be 100% correct :smiley:

  1. I’m pretty sure that Input.GetKeyDown should or can only be called from within the Update() class. Here more about that: link text
  1. (I’m not to sure about this one) You could deactivate the If() statement as soon as it was used once.
    private bool PressedKey;
    void Start(){
    PressedKey=false;
    }

     void OnTriggerStay2D(Collider col) {
         if(col.gameObject.name == "Character") {
             if (PressedKey==false){
                 if(Input.GetKeyDown(KeyCode.Z)) {
                      PressedKey=true;
                      times ++ ;
                      print("Called :" + times) ;
                 }
             } 
         }
     }
    

And then set PressedKey back to false as soon as you want to!

Hope I’ve helped you!