Can't create UWidgetComponent for non player actor in C++.

Hi all.

I’m converting a blueprint class to C++ and one of the objects in the actor is a WidgetComponent, which is being rendered in 3D with a button widget.

I’m trying to declare the widget component in the .h file with:

UPROPERTY(VisibleAnywhere, BlueprintReadWrite)
class UWidgetComponent* IconWidget;

and in .cpp with:

IconWidget = CreateDefaultSubobject(TEXT(“Widget”));
IconWidget->SetupAttachment(GetRootComponent());
IconWidget->SetWidgetSpace(EWidgetSpace::World);
IconWidget->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
IconWidget->SetDrawSize(FVector2D(256.0f, 256.0f));
IconWidget->SetVisibility(true);
IconWidget->RegisterComponent();

However, doing this gives me 285 errors from all types of source files.

I have included the Components/WidgetComponent.h, and am unsure of how to get it to work.

Am i better off just adding the empty widget component via blueprint, or what am i doing wrong?

Just to add, most articles i find look at using widget components and specifying widgets, rather than creating an empty ocmponent.

Hey, i think you use CreateDefaultSubobject the wrong way, try :

IconWidget =CreateDefaultSubobject<UWidgetComponent>(TEXT("Widget"));

I noticed the typo when i posted, just corrected it, sadly that doesn’t help.

Thanks anyway.

then, could you post the full output log ?

Hi.

Can you update your comment to an answer please.

Cheers.

Do you have the proper dependencies set up in your project’s build.cs file? Depending on what you plan to do with your widget, your project may need to depend on UMG, Slate, and/or SlateCore.