静态加载类和资源:指在编译时加载,并且只能在构造函数中编写代码
.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(TEXT("MyScene")); MyMesh = CreateDefaultSubobject (TEXT("MyMesh")); MyParticle = CreateDefaultSubobject (TEXT("MyParticle")); MyBox = CreateDefaultSubobject (TEXT("MyBox")); MyAudio = CreateDefaultSubobject (TEXT("MyAudio")); MyChildActor = CreateDefaultSubobject (TEXT("MyChildActor")); //设置父子层级关系 RootComponent = MyScene; MyMesh->SetupAttachment(MyScene); MyParticle->SetupAttachment(MyScene); MyBox->SetupAttachment(MyScene); MyAudio->SetupAttachment(MyBox); MyChildActor->SetupAttachment(MyScene); //静态加载资源:设置Component中的属性值 static ConstructorHelpers::FObjectFinder TempMesh(TEXT("/Script/Engine.StaticMesh'/Game/StarterContent/Shapes/Shape_Cone.Shape_Cone'")); //引用一个StaticMesh资产,并存储到变量“TempStaticMesh”。FObjectFinder:查找Object MyMesh->SetStaticMesh(TempMesh.Object); //调用“SetStaticMesh”的方法,设置MyMesh组件的StaticMesh属性值 static ConstructorHelpers::FObjectFinder TempParticle(TEXT("/Script/Engine.ParticleSystem'/Game/StarterContent/Particles/P_Fire.P_Fire'")); MyParticle->SetTemplate(TempParticle.Object); static ConstructorHelpers::FObjectFinder TempAudio(TEXT("/Script/Engine.SoundWave'/Game/StarterContent/Audio/Collapse01.Collapse01'")); MyAudio->SetSound(TempAudio.Object); //静态加载资源:设置ChildActor组件中的ChildActorClass属性值 static ConstructorHelpers::FClassFinderTempActor(TEXT("/Script/Engine.Blueprint'/Game/StarterContent/Blueprints/Blueprint_CeilingLight.Blueprint_CeilingLight_C'")); //注意这里是FClassFinder:查找Class。注意被引用的Actor要加后缀”_C“ MyChildActor->SetChildActorClass(TempActor.Class); //注意这里是TempActor.Class }
猜你喜欢
网友评论
- 搜索
- 最新文章
- 热门文章