- Home /
Ensure that function only gets called once in a frame
How do I ensure that a function cannot be called more than once in a single frame? I have is so that the left trigger activates the jump function if pressed and the right trigger also activates the jump function if pressed. You can only jump if your player is grounded. I found that when I press both triggers at the same time, it runs the jump function twice (and i go twice as high), but I only want it to run it once if both are pressed at the same time.
If you check for those in the same function you can do 'else if' for the second button.
You can also create a bool that you set to true at the beginning of your jump method, set to false at the beginning of Update (or in LateUpdate, probably this is better) and if the bool is true when you try to jump, you just don't.
Answer by viknesh2020 · Sep 26, 2018 at 10:54 AM
You can consider the following,
private bool callOnce;
void Update(){
if(Input.LeftTrigger || Input.RightTrigger){
callOnce = true;
}
if(callOnce){
callOnce = false;
Jump();
}
}
public void Jump(){
*//Jump script goes here*
}
I am not sure what sort of Input you are using for Jump function. There is a difference between GetKey and GetKeyDown functions. You can refer below,
GetKey returns true while the user holds down the key GetKeyDown returns true during the frame the user starts pressing down the key.
Considering your question, I assume you have to use GetKeyDown for calling your Jump function once at a single frame.
Your answer
Follow this Question
Related Questions
Calling a method once in update 1 Answer
Integer Getter Method always returns zero 3 Answers
How can I call a method from another script? 3 Answers
what is wrong whis this? 1 Answer
Is it possible to assign custom functions to a Scriptable Object? 3 Answers