How to show/hide a menu with a single key?

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

I have a simple routine attached to my Player node to show/hide a menu screen when the Enter key is pressed. I can’t figure out how to not have it disappear immediately, as the key press seems to register in multiple frames and trigger both “if” statements.

Is there a way to handle input like this without a timer node to space the input events?

func _process(delta):
	
	if Input.is_action_pressed("menu"):
		var menu = MenuScene.instance()
		
		if menu.is_inside_tree():
			menu.queue_free()
			
		else:
			add_child(menu)
:bust_in_silhouette: Reply From: Pieter-Jan Briers

You want Input.is_action_just_pressed() instead. It’s only valid on the first frame the input was pressed, so it’s perfect for this case.

:bust_in_silhouette: Reply From: volzhs

you should not create an instance of MenuScene every time.

var menu = MenuScene.instance()

func _ready():
    menu.visible = false
    add_child(menu)

func _process(delta):
    if Input.is_action_pressed("menu"):
        menu.visible = !menu.visible

in another way

var menu = MenuScene.instance()

func _process(delta):
    if Input.is_action_pressed("menu"):
        if menu.is_inside_tree():
            remove_child(menu)
        else:
            add_child(menu)