UpaJah
UpaJah

Reputation: 7334

Unreal 4.24.3 : How to Declare UPROPERTY() inside .cpp file

What I want to do:

Create a USceneComponent at Runtime in an Actor class

    USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

What works:

Defining UnitDesign at Header File(.h) works without issues..

UPROPERTY(VisibleAnywhere)  //I can see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

What does not work for me:

Defining UnitDesign at CPP File(.cpp) inside BeginPlay() of Actor class-

UPROPERTY(VisibleAnywhere)  //I can NOT see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

Any pointers appreciated.

Upvotes: 0

Views: 548

Answers (1)

George
George

Reputation: 2120

If you always want to create the UnitDesign SceneComponent then you can use CreateDefaultSubobject (c'tor only) :

/* .h */
UCLASS()
class AYourActor : public AActor
{
    GENERATED_BODY()

public:
    AYourActor(FObjectInitializer const& ObjectInitializer);

    UPROPERTY(VisibleAnywhere)
    USceneComponent* UnitDesign;
};

/* .cpp */
AYourActor::AYourActor(FObjectInitializer const& ObjectInitializer) :
    UnitDesign(nullptr) /* this is only needed if UnitDesign is not initialized below */
{
    UnitDesign = CreateDefaultSubobject<USceneComponent>(TEXT("Unit Design"));
}

If it's an optional thing then that's a bit more complicated, you can create a component later than the c'tor but you'll need to be a bit more conscious about when to get it to play nice with VisibleAnywhere. The code for that would just be

UnitDesign = NewObject<USceneComponent>(this, FName(*ID));
UnitDesign->RegisterComponent();

The sneaky way to refresh the property panel is to call :

GEditor->SelectActor(this, true, true);
GEditor->SelectNone(true, true);

The "proper" way is to call SDetailsView::ForceRefresh from a IDetailCustomization. Fair warning, it's a huge arse.

Side note that UPROPERTY() can only be used in a .h file as it needs to be visible to the Unreal Header Tool.

Upvotes: 3

Related Questions