问题描述
以下代码一直困扰着我:
ARollingBall::ARollingBall()
{
UStaticmeshComponent* sphere;
sphere = CreateDefaultSubobject<UStaticmeshComponent>(TEXT("ball"));
static ConstructorHelpers::FObjectFinder<UStaticmesh> SphereVisualAsset(TEXT("/Engine/BasicShapes/Sphere"));
sphere->SetupAttachment(RootComponent);
if (SphereVisualAsset.Succeeded()) {
sphere->SetStaticmesh(SphereVisualAsset.Object);
}
}
也就是说,我对路径进行了硬编码。如果我决定要在路上使用不同的对象怎么办?想象一下,我有多个 pawn 全部硬编码以使用此资产。在 cpp 中,没有简单的方法可以更改所有这些引用。我有一个好主意,将我的网格选择公开给蓝图,以利用 Unreal 的参考处理,如下所示:
UPROPERTY(EditDefaultsOnly,Category = "References")
UStaticmesh * m_staticmesh;
但是,当我使用蓝图从此类继承并设置默认网格(m_staticmesh)时,以下内容不会创建网格:
ARollingBall::ARollingBall()
{
UStaticmeshComponent* sphere;
sphere = CreateDefaultSubobject<UStaticmeshComponent>(TEXT("ball"));
sphere->SetupAttachment(RootComponent);
if (m_staticmesh) {
sphere->SetStaticmesh(m_staticmesh);
}
}
我使用的是 Unreal 4.21.2 两种方法都可以编译,但后者无法工作。
任何有关如何正确使用上述功能的建议表示赞赏。如果您知道避免硬编码路径的更好方法,请告诉我。
解决方法
通常根本不推荐使用静态构造函数助手。
由组件组成的 Actor 并利用虚幻反射系统将这些组件及其属性公开给编辑器以在蓝图中进行修改是理想的模式。
/* Weapon Mesh. */
UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category = "Weapons")
UStaticMeshComponent* Mesh;
在创建该 Actor 的子蓝图后,使用 VisibleAnywhere
标记在构建期间创建的组件将使其显示在 Actors 组件视图中的组件层次结构中。
然后您将有权修改其属性,例如静态网格体。
在使用 UPROPERTY 以及所有函数和类说明符及其元数据时,了解什么是有效的属性说明符非常有用。