C++ PickupActor - how to add UserWidget to WidgetComponent at runtime?

Hi all,

A quick overview of what I want to achieve:

A BP_Pickup object that derives from my Pickup Actor C++ class.
The name of the Pickup object is shown above it using my PickupItemName Widget.
All in C++, with WidgetSpace = Screen & DrawAtDesiredSize = true


I have a Pickup Actor created in C++ with:

  • Root = SceneComponent
  • UStaticMeshComponent
  • UWidgetComponent.

I need the WidgetComponent since I need to set the SetWidgetSpace, SetDrawAtDesiredSize of the widget in C++.

I also made a C++ UPickupItemName Widget - Inherits from UUserWidget:

  • Has a UTextBlock that will show the name of the Pickup actor.
UPROPERTY(BlueprintReadOnly, meta=(BindWidget))
	class UTextBlock* PickupName;

If I understand correctly I still have to actually make a Widget blueprint child deriving from this C++ UPickupItemName? Where I will have to create a UTextBlock named “PickupName”.
Not like with an actor where you put SceneComponents, box Collisions, etc and add them through CreateSubobject<>() & SetupAttachment()?

  • It also has a SetPickupName function that will SetText(…) the UTextBlock.

My Pickup.h:

UPROPERTY(EditDefaultsOnly)
class UWidgetComponent* Widget;

UPROPERTY(EditAnywhere, Category = "Pickup")
TSubclassOf<class UUserWidget> WidgetClass;

UPROPERTY() 
class UPickupItemName* PickupWidget;

My Pickup.cpp:

Constructor:

Widget = CreateDefaultSubobject<UWidgetComponent>(TEXT("Widget"));
Widget->SetupAttachment(SceneComponent);
Widget->SetWidgetSpace(EWidgetSpace::Screen);
Widget->SetDrawAtDesiredSize(true);

BeginPlay:

...
PickupWidget =  CreateWidget<UPickupItemName>(GetWorld(), WidgetClass);
if(PickupWidget){
		PickupWidget->SetPickupName(PickupName);
		PickupWidget->AddToViewport(); 
}

In all tutorials I’ve seen, they never seem to use a WidgetComponent.
They all use just the CreateWidget.
But then I have no way it seems to adjust the WidgetSpace & DrawAtDesiredSize in C++.

Is there a way to link this Created Widget to the widgetComponent?
I’ve tried SetWidget(), but that didn’t seem to work.

When I run this, I can see with a ulog that the SetPickupName function is called and the name is changed, but I still can’t see the text, I keep seeing the default UTextBlock Text.

I’ve been looking all day for a solution, but most of widget tutorials are in blueprint or just use a userwidget to show something on the player hud, not actually on another actor…

Thanks already for any help.