How to remove and add a child pressing a button.

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

I’m new to Godot and want to switch between two scenes when I press spacebar. I wrote this, but it is not working. Does anyone know why?

Code:

extends Node
export (PackedScene) var In
func switch():
    if Input.is_action_pressed("ui_accept"):
	    var in = In.instance()
	    add_child(in)
	    remove_child($Out)

How are you calling switch?

Also note that in is a language keyword, you cannot use it for a variable name. Use another name, like next_scene.

Zylann | 2020-03-12 19:11

I changed the names, but it still doesn’t work. If I use a Timer to activate the switch, it works, but not with the input.

Rykasi | 2020-03-13 23:13

if Input.is_action_pressed("ui_accept"):

This is probably the line that prevents your code from running.
That line means “is the key bound to ui_accept currently pressed”, is it what you intended?

Zylann | 2020-03-13 23:20