Adding multiple of the same child to a scene

Godot Version

4.4.1

Question

I’m trying to instance a bunch of the same scene into a larger scene (basically making a board where each individual piece needs to have its own information, etc etc)

I get the error that

E 0:00:01:169   combat_board.gd:11 @ _ready(): Can't add child 'Combat Board Node' to 'Combat Board', already has a parent 'Combat Board'.
 <C++ Error>   Condition "p_child->data.parent" is true.
 <C++ Source>  scene/main/node.cpp:1653 @ add_child()
 <Stack Trace> combat_board.gd:11 @ _ready()

my code for adding the children is:

const COMBAT_BOARD_NODE = preload("res://combat_board_node.tscn")

func _ready():
	var combat_node = COMBAT_BOARD_NODE.instantiate()
	var i := 0
	while i < 3:
		add_child(combat_node)
		combat_node.node_data.emit("Ally", i)
		add_child(combat_node)
		combat_node.node_data.emit("Enemy", i+3)
		i += 1

Is there another a way to add children to the scene that fixes this problem?

I’m very new to Godot, however I think your problem is that you call .instantiate() just once - that creates a single new node, which you then try to add to the scene multiple times. Instead you need to call .instantiate() multiple times - each time it will make a new separate node.

4 Likes

You are creating only one instance of combat node, but it seems you need six of them.

const COMBAT_BOARD_NODE = preload("res://combat_board_node.tscn")

func _ready():
	var combat_node 
	for i in 3:
		combat_node = COMBAT_BOARD_NODE.instantiate()
		add_child(combat_node)
		combat_node.node_data.emit("Ally", i)

		combat_node = COMBAT_BOARD_NODE.instantiate()
		add_child(combat_node)
		combat_node.node_data.emit("Enemy", i+3)
3 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.