Can't read properties from UWidgetComponent in C++

Hi, I’m trying to create a health bar widget for my actors. The problem is that I can’t access any variables and methods of created widget from my actor.

I started from creating a C++ widget:

 class DRONE_API UHealthBar3d : public UUserWidget
{
	GENERATED_BODY()	
	
public:

	UPROPERTY(EditAnywhere, meta = (BindWidget))
		UTextBlock* HealthText = nullptr;
	UPROPERTY(EditAnywhere, meta = (BindWidget))
		UProgressBar* HealthBar;
	float DefaultHealth = 1;
}

And creating a blueprint child of it with actual implementation of text block and progress bar, then in my actor class .h I have:

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
		TSubclassOf<UHealthBar3d> HealthBarWidget;

	UPROPERTY(EditAnywhere, BlueprintReadWrite)
	UWidgetComponent* HealthBarWidgetComp = nullptr;

and I create it in my constructor:

HealthBarWidgetComp = CreateDefaultSubobject<UWidgetComponent>(TEXT("Test"));

to be able to see the widget in screen I have to do that in BeginPlay:

	HealthBarWidgetComp->SetWidgetClass(HealthBarWidget);

After creating a BP from this actor and setting HealthBarWidget to HealthBarWidgetBP (child of UHealthBar3d) I can see that my widget appears in scene. Now I have to modify the values there, and I was expected just to do something like this in tick function:

HealthBarWidget.DefaultHealth = 150;

But actually I didn’t manage to access any of my properties or functions at all, what did I miss to be able to do so?

Well, actually it’s a classic situation when you figure out the solution after 10 minutes you post a question :slight_smile: By doing that I managed to access all I need:

	auto HealBarUserWidget = Cast<UHealthBar3d>(HealthBarWidgetComp->GetUserWidgetObject());
	if (HealBarUserWidget)
	{
		HealBarUserWidget->SetHealth(Health);
	}

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