My chest won't spawn an item

Godot Version

extends Area2D

class_name Chest

var health := randi_range(5, 10)

@export var javalin : PackedScene
@export var knife : PackedScene
@export var torch : PackedScene
@export var axe : PackedScene
@export var bow : PackedScene

func _process(delta):
	if health <= 0:
		spawnRngLoot()

func take_damage(damage):
	health -= damage

func spawnRngLoot():
	var loot = 0
	print(loot)
	var item
	match loot:
		# Javalin.
		0:
			item = javalin.instantiate()
		# Knife.
		1:
			pass
		# Torch.
		2:
			item = torch.instantiate()
		# Axe.
		3:
			pass
		# Box.
		4:
			pass
		# Armour
		5:
			pass
		# Score pickup.
		6:
			pass
	if item != null:
		item.transform = transform
	queue_free()

Question

So what's supposed to happen is that when the chest is destroyed its supposed to pick a random number (I have it set to zero for test purposes), and depending on what number it spawns the corresponding item, but when I destroy it; it doesn't spawn in the item.

You instantiate the item, but you also need to add it to the scene. Use add_child.
Or in your case: get_root().add_child(item) since otherwise you’ll also destroy the spawned item right away.

1 Like

This doesn’t answer your question but it’ll save you frustration.
Get rid of your process function and do this instead

func take_damage(damage):
	health -= damage
        if health <= 0:
	       spawnRngLoot()

The way you had it would have spawned an item every frame

1 Like

It’s probably better to use either get_parent().add_child(item) or get_tree().current_scene.add_child(item). (I don’t think get_root() is evene accessible in that scope?)

I meant to say get_tree().root but I think OP got the idea either way.

1 Like

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