I need help switching TextureRec through code

Godot Version

4.6

Question

I am trying to implement a heart HUD in my game, I have a Canvas layer scene with an HBoxContainer that adds child TextureRec scenes with my hearts in it. I’m currently trying to get it to replace the “full heart” scenes with the “empty heart” ones, which are different scenes, my code is attached to the Canvas layer.

extends CanvasLayer

@export_file ("*.tscn") var heart_full : String
@export_file ("*.tscn") var heart_empty : String
@export var health_component : HealthComponent
@export var hbox : HBoxContainer

func _ready() -> void:
	setup_hp()

func setup_hp():
	#clean_current_representation()
	var Health_Points: int
	draw_hearts(Health_Points)

func add_bottle():
	var hearte = load(heart_empty)
	var empty_bottle = hearte.instantiate()
	hbox.add_child(empty_bottle)

func _on_health_component_grant_health(HP: int) -> void:
	draw_hearts(HP)

func draw_hearts(HP:int):
	for x in HP :
		var heartf = load(heart_full)
		var heart_instance = heartf.instantiate()
		hbox.add_child(heart_instance)

func clean_current_representation():
	for child in hbox.get_children():
		child.queue_free()

func _on_health_component_health_changed(diff : int) -> void:
	clean_current_representation()
	add_bottle()

When I get hit the first time it spawns the first “empty heart” but it doesn’t on the second. I’m not quite sure what to do about it.

In _on_health_component_health_changed you call clean_current_representation first, which deletes all the children of hbox, and then you add one bottle.

1 Like

Thank you for the help, I ended up just stacking a second HBoxContainer underneath instead of spawning new TextureRec when the character gets hit, and that seems to work well enough for now.