I'm using Godot 3.0.6. I am able to instantiate a scene by pressing a key, but only once. Here is my code in GDScript:
extends KinematicBody
var cube = load("res://Scenes/Cube.tscn").instance()
var ball
var velocity
func _ready():
ball = get_node(".")
func _process(delta):
pass
func _physics_process(delta):
if Input.is_action_pressed("ui_up"):
get_tree().get_root().add_child(cube)
If I try adding more than one cube into the scene, I get an error:
Can't add child 'Cube' to 'root', already has a parent 'root'.
What am I doing wrong?
You're trying to add the same cube
instance to the scene tree repeatedly. Just load the scene and don't create an instance immediately. Create the new instances when the key gets pressed and add them to the scene tree.
var cube = preload("res://Scenes/Cube.tscn")
func _physics_process(delta):
if Input.is_action_pressed("ui_up"):
# Create a new instance here.
get_tree().get_root().add_child(cube.instance())