找回密码
 立即注册
查看: 231|回复: 0

最简单的 UE 4 C++ 教程 —— 编程实现添加一个组件【四】

[复制链接]
发表于 2023-4-11 21:58 | 显示全部楼层 |阅读模式
【原教程是基于 UE 4.18,我是基于 UE 4.25】
英文原地址
接上一节,在本教程中,我们将添加一个广告牌组件(Billboard)到我们的 Actor 对象上。在 UE4 编辑器中也可以很容易地添加组件,但是这次让我们通过编程来实现。
首先,我们将创建一个名为 AddBillboardComp 的新的 Actor 子类。请记住,如果您用不同的名字的话,请确保在使用了该头文件和 cpp 文件的地方都相应更改了名称。
在头文件中,我们将创建一个继承自 UBillboardComponent 类的变量。这将允许我们添加一个广告牌组件并使用它的属性。
AddBillboardComp.h
  1. #pragma once
  2. #include "CoreMinimal.h"
  3. #include "GameFramework/Actor.h"
  4. #include "AddBillboardComp.generated.h"
  5. UCLASS()
  6. class UNREALCPP_API AAddBillboardComp : public AActor
  7. {
  8.         GENERATED_BODY()
  9.        
  10. public:       
  11.         // Sets default values for this actor's properties
  12.         AAddBillboardComp();
  13. protected:
  14.         // Called when the game starts or when spawned
  15.         virtual void BeginPlay() override;
  16. public:       
  17.         // Called every frame
  18.         virtual void Tick(float DeltaTime) override;
  19.         // declare point light comp
  20.         UPROPERTY(VisibleAnywhere)
  21.         class UBillboardComponent* MyBillboardComp;
  22.        
  23. };
复制代码
在 cpp 文件中,我们将把广告牌组件添加到该 actor 类中。向 actor 类中添加任何组件的这个过程都是非常类似的
如果想在 actor 中使用任何组件类,就必须在 cpp 文件中包含组件头文件。那么,让我们将公告牌组件文件添加到代码中。
  1. #include "Components/BillboardComponent.h"
复制代码
在本教程中,我们将在 actor 子类的构造函数中添加组件。这将确保组件在添加到场景时被添加到 actor 中。
创建公告牌组件的默认子对象
  1. MyBillboardComp = CreateDefaultSubobject<UBillboardComponent>(TEXT("Root Billboard Comp"));
复制代码
并使其可见
  1. MyBillboardComp->SetHiddenInGame(false, true);
复制代码
使公告牌组件成为根组件
  1. RootComponent = MyBillboardComp;
复制代码
最后完整的 cpp 代码如下
  1. #include "AddBillboardComp.h"
  2. // include billboard comp
  3. #include "Components/BillboardComponent.h"
  4. // Sets default values
  5. AAddBillboardComp::AAddBillboardComp()
  6. {
  7.         // Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
  8.         PrimaryActorTick.bCanEverTick = true;
  9.         MyBillboardComp = CreateDefaultSubobject<UBillboardComponent>(TEXT("Root Billboard Comp"));
  10.         MyBillboardComp->SetHiddenInGame(false, true);
  11.         RootComponent = MyBillboardComp;
  12. }
  13. // Called when the game starts or when spawned
  14. void AAddBillboardComp::BeginPlay()
  15. {
  16.         Super::BeginPlay();
  17.        
  18. }
  19. // Called every frame
  20. void AAddBillboardComp::Tick(float DeltaTime)
  21. {
  22.         Super::Tick(DeltaTime);
  23. }
复制代码
最终效果如图所示

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-5-6 03:25 , Processed in 0.141416 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表