How to limit key press so that it only calls a function once?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Macryc

Hi All. I have an input function that looks like this:

func _input(event):
	if event.is_action_pressed("key_L"):

in _ready() I also have this:


Yet, pressing L triggers the function multiple times.

I also tried using Input.is_action_just_pressed but that also triggers the function like 6 times…

How do I limit that to a single funtion call?

#jump input
if Input.is_action_just_pressed("ui_up") and is_on_floor():
	v.y -= jumpforce

Here is a snippet of code that i have for a character jumping in a 2D world which works just fine with is_action_just_pressed. I don’t want to leave you with that though because your situation seems to stretch a little further than that. Could you give more context such as implementation? is_action_just_pressed may be doing what it should but the problem may stem from what’s inside the function.

Panda_Scientist | 2020-07-08 20:05

thing is, there isn’t anything inside the function save for a print("something") which prints 6 times with is_action_just_pressed used in _process().

Macryc | 2020-07-08 20:08

I have a chest object from the game that uses that snippet of code that I just tested on that uses is_action_just_pressed to open the chest, and it only prints my echo once, I’m not certain what could be happening here but what I usually do in a situation like this to solve the problem is rewrite a simplified version in another project, and see if it behaves the same. That’s what I would suggest to do in this situation.

Panda_Scientist | 2020-07-08 20:39

ok i wasn’t entirely honest - my function does something besides just printing. What it does is gets nodes in a group (array) and instances a mesh node for each. It then appends the instanced meshes to second array and prints that second array. The number of items in the new array is always correct but it should only print once. It printing 6 times suggests that the function is called 6 times…

Macryc | 2020-07-08 20:49

I also just tried removing everything from the function and replacing it with a simple print("ok") and I got 9 ok’s printed…

Macryc | 2020-07-08 20:53

OK forget everything I just said, I was being stupid. I attached the input code to a generic script that is attached to several nodes on the map. Key press was triggering the function as many times as there were instances of the script in the tree, which makes total sense. I’ve now moved the function and input code to a singleton and the problem is gone…

Macryc | 2020-07-08 21:07

Well that’s perfect! I’m glad you identified the problem and found a solution.

Panda_Scientist | 2020-07-08 22:13