How to create WidgetComponent with a UUserWidget reference in C++ code?

I have a simple AUnit actor which resembles a tank. I also have a ActorComponent ‘HealthComponent’ attached through it via code. The HealthComponent takes care of HP and should also spawn the health bar above the tank unit.

Relevant header of HealthComponent (UActorComponent):

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Health Bar", meta = (BindWidget) )
	class TSubclassOf<class UHealthBar> HealthBarClass;
	UPROPERTY(BlueprintReadOnly, Category = "Health Bar"/*)
class UHealthBar* HealthBarWidget;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Health Bar", meta = (BindWidget) )
	class TSubclassOf<class UEntityHealthBar> EntityClass;
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Health Bar"/*, meta = (BindWidget)*/ )
	class UEntityHealthBar* EntityComp;

Relevant cpp of HealthComponent (UActorComponent):

UHealthComponent::UHealthComponent()
    {
       EntityComp = CreateDefaultSubobject<UEntityHealthBar>(TEXT("hp_widget_component"));
    
       // This "HealthBarClass" variable is always NULL !!!
       EntityComp->SetWidgetClass(HealthBarClass);
    }

The variable “HealthBarClass” always seems to be NULL whenever this part of code is reached. Even if the unit blueprint i’ve created has set the “HealthBarClass” to the correct blueprint with the desired UI healthbar in it.

I’ve seen other examples online where people use some sort of helper function instead to find the “TSubclassOf” via a string address (example: “/ui/healthbar”). I thought this was messy and prone to errors in case i ever move that blueprint. So i want my HealthComponent to hold a reference to the UI blueprint. so that when i create the WidgetComponent for my unit actor, i can set the WidgetComponent’s Widget value to the stored blueprint.

Hi there! You can make it in several steps:

And smth more: “HealthBarClass variable is always NULL” because base constructor is called before the one that use value from Blueprint, at this moment this proprty is actually NULL.

Thanks, I managed to spawn it by moving SetWidgetClass and InitWidget into the BeginPlay() function.

However, All values of the WidgetComponent are always the ones defined in C++. When I create a blueprint for this class and adjust some of the WidgetComponent values, they rever to either default (UE4 default) or C++ values (if defined). So, changing values in the blueprint - for exmpale Draw Size or Pivot - always are set to the c++ values once dragged into the scene or spawned in.
So making two different blueprints with slightly different draw sizes for example would result in two identical widgetcomponents for the two blueprints based on the c++ class.

Check it all in 4.23 - dont find anything strange… Can you try your code in this version?