Why can't I add multiple instances of a node?

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

When I try to instantiate an object using this code…

extends Node2D

onready var sandScene = load("res://Scenes/Sand.tscn")
onready var sand = sandScene.instance()

func _physics_process(delta):
	if Input.is_action_just_pressed("place_object"):
		sand.position = Vector2(rand_range(10, 980), rand_range(10, 980))
		add_child(sand)

… it comes up with the error:

add_child: Can’t add child ‘Sand’ to ‘Objects’, already has a parent
‘Objects’.

I’m new to using godot and gdscript so I might have a really obvious mistake but all the videos I have watched haven’t helped.

Try

if Input.is_action_just_pressed("place_object"):
        var s = sandScene.instance()
         s.position = Vector2(rand_range(10, 980), rand_range(10, 980))
         add_child(s)

ramazan | 2022-08-07 20:43

:bust_in_silhouette: Reply From: SnapCracklins

Weird question: why is this in the physics process? Do you need this triggering every physics step?

Seems like input would be a better place… Not sure if that solves your problem.

EDIT: Also adding Ramazan’s fix, which looks right (and often is).

extends Node2D

onready var sandScene = load("res://Scenes/Sand.tscn")
onready var sand = sandScene.instance()

func _input(event):
       if event.is_action_pressed("place_object"):
             var s = sandScene.instance()
             s.position = Vector2(rand_range(10, 980), rand_range(10, 980))
             add_child(s)

Thx for the answer, it works perfectly

Cakey49 | 2022-08-08 06:02