Creating multiple instances of the same node

Godot Version

v4.5.stable.steam [876b29033]

Question

I’m somewhat new to godot. I’m trying to make Question Mark Blocks that can drop multiple coins like in the Super Mario games. If you hit the block too fast, the coin it drops will either glitchly move, and then cause an error, or if the coin has despawned, it will break.
Code:

extends StaticBody2D

@export var isquestionblock = true
@onready var area_2d: Area2D = $Area2D
@onready var animated_sprite: AnimatedSprite2D = $AnimatedSprite2D
const coin_scene = preload("res://Scenes/falling_coin.tscn")
var coin = coin_scene.instantiate()
var coins_in_block = 10

func _ready() -> void:
	if isquestionblock:
		animated_sprite.play("Idle")
	else:
		animated_sprite.play("Brick")

func _on_area_2d_body_entered(body: Node2D) -> void:
	if coins_in_block > 0:
		coins_in_block -= 1
		get_parent().add_child.call_deferred(coin)
		coin.global_position = global_position + Vector2(0, -16)
	else:
		animated_sprite.play("Hit")
		area_2d.queue_free()

Errors:

Coin despawned:
E 0:00:03:355   add_child: Can't add child 'CharacterBody2D' to 'Node2D', already has a parent 'Node2D'.
  <C++ Error>   Condition "p_child->data.parent" is true.
  <C++ Source>  scene/main/node.cpp:1685 @ add_child()
E 0:00:04:156   _on_area_2d_body_entered: Invalid assignment of property or key 'global_position' with value of type 'Vector2' on a base object of type 'previously freed'.
  <GDScript Source>question_mark.gd:20 @ _on_area_2d_body_entered()
  <Stack Trace> question_mark.gd:20 @ _on_area_2d_body_entered()

Before despawn:
E 0:00:01:817   add_child: Can't add child 'CharacterBody2D' to 'Node2D', already has a parent 'Node2D'.
  <C++ Error>   Condition "p_child->data.parent" is true.
  <C++ Source>  scene/main/node.cpp:1685 @ add_child()
E 0:00:02:534   _on_area_2d_body_entered: Invalid assignment of property or key 'global_position' with value of type 'Vector2' on a base object of type 'previously freed'.
  <GDScript Source>question_mark.gd:20 @ _on_area_2d_body_entered()
  <Stack Trace> question_mark.gd:20 @ _on_area_2d_body_entered()

You instantiate the coin scene only one time (at the beginning var coin = coin_scene.instantiate()), so you have only one coin to add to your scene. If you want to add multiple coins, you just have to relocate that line into the function (directly above the get_parent()... line), so each time a new coin gets instantiated.

2 Likes

This worked, thanks!

1 Like