Unreal 在CPP类中创建组件

以UStaticMeshComponent组件为例

声明并创建组件

UStaticMeshComponent 组件为例,在 *.h 文件中声明。

// 成员变量
UStaticMeshComponent* MyComponent;

在构造函数中进行初始化。

  • CreateDefaultSubobject<T>()用来创建组件。
  • RootComponent为根组件。
// 构造函数内
this->MyComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyComponent"));
RootComponent = this->MyComponent;

组件的结构设定

声明的组件可以挂载在目标组件之上,比如可以挂在SpringArm上的 camera

在 *.h 中声明,SpringArmCamera

  • 在 *.h 中进行提前声明。
// 成员变量
class USpringArmComponent* SpringArm;
class UCameraComponent* Camera;

在构造函数中进行初始化,

  • 在 *.cpp 中引入依赖头文件。
  • SetupAttachment()构建层级结构,Camera依附于SpringArm
// 构造函数内
this->SpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("SpringArm"));
this->SpringArm->SetupAttachment(RootComponent);
this->Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
this->Camera->SetupAttachment(SpringArm);

暴露组件

组件也是变量,所以可以暴露在蓝图与编辑器中,如下。

UPROPERTY(BlueprintReadWrite, VisibleAnywhere)
UStaticMeshComponent* MyComponent;