虚幻 4.24.3:如何在 .cpp 文件中声明 UPROPERTY()

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

我想做的事情:

在运行时在 Actor 中创建一个 USceneComponent class

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

什么有效:

在头文件 (.h) 中定义 UnitDesign 没有问题..

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

什么对我不起作用:

在 Actor class-

的 BeginPlay() 内的 CPP 文件 (.cpp) 中定义 UnitDesign
UPROPERTY(VisibleAnywhere)  //I can NOT see UnitDesign in World Outliner
USceneComponent* UnitDesign = NewObject<USceneComponent>(this, FName(*ID));

感谢任何指点。

如果您总是想创建 UnitDesign SceneComponent,那么您可以使用 CreateDefaultSubobject(仅限 c'tor):

/* .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"));
}

如果它是一个可选的东西,那就有点复杂了,你可以在 c'tor 之后创建一个组件,但是你需要更加注意什么时候让它与 VisibleAnywhere。代码就是

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

刷新 属性 面板的偷偷摸摸的方法是调用:

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

"proper" 方法是从 IDetailCustomization 调用 SDetailsView::ForceRefresh。公平警告,这是一个巨大的屁股。

旁注,UPROPERTY() 只能在 .h 文件中使用,因为它需要对 Unreal Header Tool 可见。