Hello!
Im trying to do a (I think) quite normal and easy thing in C++: I want an NPC to have its own 2D textblock over its head. But when all the logic was done I can’t seem to add a WidgetComponent to an instance of an Actor.
For this, I’ve created ActorWithWidgetComponent class derived from AActor, UserWidgetTest class derived from UUserWidget and WidgetComponentTest derived from UUserWidget. Then added the UserWidgetTest into the WidgetComponentTest and this last one into the ActorWithWidgetComponent (classes are brand new):
ActorWithWidgetComponent.h
UCLASS()
class ABOTTOTHETOP_API AActorWithWidgetComponentTest : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this acto properties
AActorWithWidgetComponentTest();
private:
UPROPERTY(EditAnywhere, Category = "UI")
class UWidgetComponentTest* WidgetComponentInstance;
};
ActorWithWidgetComponent.cpp
AActorWithWidgetComponentTest::AActorWithWidgetComponentTest()
{
WidgetComponentInstance = CreateDefaultSubobject<UWidgetComponentTest>(TEXT("WidgetComponent"));
WidgetComponentInstance->SetupAttachment(RootComponent);
}
WidgetComponentTest.h
UCLASS()
class ABOTTOTHETOP_API UWidgetComponentTest : public UWidgetComponent
{
GENERATED_BODY()
protected:
virtual void BeginPlay();
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "UI")
TSubclassOf<class UUserWidgetTest> UserWidgetClass;
UPROPERTY()
class UUserWidgetTest* UserWidgetInstance;
};
WidgetComponentTest.cpp
void UWidgetComponentTest::BeginPlay()
{
Super::BeginPlay();
if (UserWidgetClass)
{
SetWidgetClass(UserWidgetClass);
}
UserWidgetInstance = Cast<UUserWidgetTest>(GetUserWidgetObject());
}
UserWidgetTest.h
UCLASS()
class ABOTTOTHETOP_API UUserWidgetTest : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(meta = (BindWidget))
UTextBlock* TextBlock;
};
UserWidgetTest.cpp – empty
Now the problem is as it follows:
When I instanciate all this classes into blueprints; get the UserWidget INTO the WidgetComponent and this last one INTO the Actor, when I compile de Actor (in editor) the variable containing the WidgetComponent nulls its self and I can’t seem to do anything about it.
Sorry for the long post, I’ve been days with this and I’m kind of desesperated, thanks in advance for any kind of help.