0 votes

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.

Godot version 3.5
in Engine by (15 points)

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)

1 Answer

+1 vote
Best answer

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)
by (548 points)
selected by

Thx for the answer, it works perfectly

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.