声明并创建组件
以 UStaticMeshComponent
组件为例,在 *.h 文件中声明。
// 成员变量
UStaticMeshComponent* MyComponent;
在构造函数中进行初始化。
CreateDefaultSubobject<T>()
用来创建组件。RootComponent
为根组件。
// 构造函数内
this->MyComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyComponent"));
RootComponent = this->MyComponent;
组件的结构设定
声明的组件可以挂载在目标组件之上,比如可以挂在SpringArm
上的 camera
。
在 *.h 中声明,SpringArm
和 Camera
。
- 在 *.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;