How to add a child to a child node if the child is a scene

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

I want that when a key is pressed, the code adds a new child “menu” in which all the settings will be. But I’ve already tried a lot, but it doesn’t work all the same. Even hiding and showing this node will do fine for me. Here is the final code:

func menu():
    If Input.is_action_pressed("menu"):
        var menu = load("res://Singleplayer/Scenes/Menu.tscn").instance()
        add_child(menu)
:bust_in_silhouette: Reply From: timothybrentwood

The way your code is written assumes that the user is pressing the menu action at the exact time that your menu() function is called in your code. This is likely not ever going to be the case.

I would first add the your menu scene as a child of the scene then hide it, then use _input() to show it:

var menu_scene 

func _ready():
    menu_scene = load("res://Singleplayer/Scenes/Menu.tscn").instance()
    menu_scene.visible = false
    add_child(menu_scene)

func _input(event: InputEvent) -> void:
	if event.is_action_released("menu"):
	    menu_scene.visible = not menu_scene.visible

thanks it helped

Donbosik | 2021-11-11 10:28