How do I force unique style boxes for a child node progress bar with code?

Godot Version

4.6.2

Question

I’m attempting to create a generic health bar UI scene to place above enemies / reuse in a player HUD - I’m 90% of the way there but having trouble updating the color of the health bar via Style settings when I have multiple instances of the health bar in game.

The below script works if I add a health bar to just one enemy type. Once I add it to a second enemy type, the color updates break.

class_name HealthBar
extends Control

const LOW_HEALTH_PERCENTAGE : float = 0.3

@export var health_component : HealthComponent
@export var alignment : GameConstants.Alignment = GameConstants.Alignment.ENEMY

var low_health_threshold : int

@onready var progress_bar: ProgressBar = $ProgressBar

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	progress_bar.max_value = health_component.MAX_HEALTH
	progress_bar.min_value = 0
	progress_bar.value = health_component.health
	low_health_threshold = health_component.MAX_HEALTH * LOW_HEALTH_PERCENTAGE
	progress_bar.set_fill_mode(ProgressBar.FILL_BEGIN_TO_END)

	
func _process(delta: float) -> void:
	
	# Update health value
	progress_bar.value = health_component.health
	
	# low health indication
	if (progress_bar.value < low_health_threshold):
		print("be red")
		progress_bar.get("theme_override_styles/fill").bg_color = Color.RED
	else:
		progress_bar.get("theme_override_styles/fill").bg_color = Color.GREEN
	
	# Hide enemy health bars when full
	if health_component.my_alignment == GameConstants.Alignment.ENEMY:
		if progress_bar.value == progress_bar.max_value:
			progress_bar.visible = false
		else:
			progress_bar.visible = true

I know mostly why this is - Styleboxes are resources and the two health bar instances are referencing the same resource. A tutorial suggested right clicking the StyleBox in the inspector and selecting “Make Unique”, but make unique is disabled in my health bar scene because there is only one instance there.

Is there a way to force unique style boxes with code for my child progress bar?

“Make Unique” will create a new resource in the editor, changing it in the editor will not change other resources. The resource is still shared in-game.

“Local to Scene” will create a new resource every time the object is instantiated, if you are changing it through scripts this is likely the better option.