静态加载类和资源:指在编译时加载,并且只能在构造函数中编写代码
.h
//增加所需组件的头文件
#include "Components/SceneComponent.h" //场景组件
#include "Components/StaticMeshComponent.h" //静态网格体组件
#include "Components/BoxComponent.h" //Box碰撞体组件
#include "Components/AudioComponent.h" //音频组件
#include "Components/ChildActorComponent.h" //子Actor组件
#include "Particles/ParticleSystemComponent.h" //粒子组件UCLASS()
class 工程名称_API AMyActor : public AActor
{//定义组件变量UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class USceneComponent* MyScene;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class UStaticMeshComponent* MyMesh;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class UParticleSystemComponent* MyParticle;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class UBoxComponent* MyBox;UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class UAudioComponent* MyAudio;//定义ChildActor组件类型变量UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MyComponent")class UChildActorComponent* MyChildActor;
}
.cpp
AMyActor::AMyActor() //注意是在这里实现,不是BeginPlay、Tick
{// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;//初始化组件变量的值MyScene = CreateDefaultSubobject<USceneComponent>(TEXT("MyScene"));MyMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyMesh"));MyParticle = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("MyParticle"));MyBox = CreateDefaultSubobject<UBoxComponent>(TEXT("MyBox"));MyAudio = CreateDefaultSubobject<UAudioComponent>(TEXT("MyAudio"));MyChildActor = CreateDefaultSubobject<UChildActorComponent>(TEXT("MyChildActor"));//设置父子层级关系RootComponent = MyScene;MyMesh->SetupAttachment(MyScene);MyParticle->SetupAttachment(MyScene);MyBox->SetupAttachment(MyScene);MyAudio->SetupAttachment(MyBox);MyChildActor->SetupAttachment(MyScene);//静态加载资源:设置Component中的属性值static ConstructorHelpers::FObjectFinder<UStaticMesh>TempMesh(TEXT("/Script/Engine.StaticMesh'/Game/StarterContent/Shapes/Shape_Cone.Shape_Cone'")); //引用一个StaticMesh资产,并存储到变量“TempStaticMesh”。FObjectFinder:查找ObjectMyMesh->SetStaticMesh(TempMesh.Object); //调用“SetStaticMesh”的方法,设置MyMesh组件的StaticMesh属性值static ConstructorHelpers::FObjectFinder<UParticleSystem>TempParticle(TEXT("/Script/Engine.ParticleSystem'/Game/StarterContent/Particles/P_Fire.P_Fire'")); MyParticle->SetTemplate(TempParticle.Object);static ConstructorHelpers::FObjectFinder<USoundWave>TempAudio(TEXT("/Script/Engine.SoundWave'/Game/StarterContent/Audio/Collapse01.Collapse01'")); MyAudio->SetSound(TempAudio.Object);//静态加载资类:设置ChildActor组件中的ChildActorClass属性值static ConstructorHelpers::FClassFinder<AActor>TempActor(TEXT("/Script/Engine.Blueprint'/Game/StarterContent/Blueprints/Blueprint_CeilingLight.Blueprint_CeilingLight_C'")); //注意这里是FClassFinder:查找Class。注意被引用的Actor要加后缀”_C“MyChildActor->SetChildActorClass(TempActor.Class); //注意这里是TempActor.Class
}