Godot Version
v4.6.1.stable.official [14d19694e]
Question
I’m trying to have a different card spawn when I click a button. But when I hit the button, I get this error: E 0:00:04:067 board.gd:10 @ spawn_card(): Required object “rp_child” is null.
<C++ Source> scene/main/node.cpp:1703 @ add_child()
board.gd:10 @ spawn_card()
next_card.gd:4 @ _on_pressed()
and this error: E 0:00:04:067 spawn_card: Invalid type in function ‘add_child’ in base ‘Node2D (board.gd)’. Cannot convert argument 1 from String to Object.
board.gd:10 @ spawn_card()
board.gd:10 @ spawn_card()
next_card.gd:4 @ _on_pressed()
I have no idea what this means or how to fix it. I’m just getting back into Godot and still very much learning. Here is my code:
extends Node2D
@export var card_types = ["malt", "water", "hops", "yeast"]
@onready var card = preload("res://scenes/card template.tscn").instantiate()
func spawn_card():
var next = card_types.pick_random()
print(next)
add_child(next)
Any help will be appreciated.
You’re trying to spawn a String as an object. It helps to assign types on everything.
extends Node2D
@export var card_types = ["malt", "water", "hops", "yeast"]
@onready var card = preload("res://scenes/card template.tscn").instantiate()
func spawn_card():
var next: String = card_types.pick_random() # This is type String
print(next)
add_child(next) #This is not an object, it's a String
You also do not want to instantiate the card as a variable, because when you go to make your second card, it will actually be the first one and you’ll get errors. I’d also recommend renaming the file “card template.tscn” to “card_template.tscn”
Try this code:
extends Node2D
@export var card_types = ["malt", "water", "hops", "yeast"]
const CARD = preload("res://scenes/card template.tscn")
func spawn_card():
var next: String = card_types.pick_random() # This is type String
print(next)
var card = CARD.instantiate()
# Assign card_type to card here somehow. Maybe...
# card.type = card_type
add_child(card)
That seemed to work. Thanks for your help!