• 初学UE5 C++②


    目录

    导入csv表格数据

    创建、实例化、结构体

    GameInstance

    Actor

    camera

    绑定滚轮控制摇臂移动

    碰撞绑定

    角色碰撞设定 

    按钮

    UI显示 

    单播代理

    多播和动态多播

    写一个接口

    其他

     NewObject 和 CreateDefaultSubobject区别


    导入csv表格数据

    创建一个object的C++类

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "UObject/NoExportTypes.h"
    5. #include "CharacterMsgObject.generated.h"
    6. USTRUCT(BlueprintType)
    7. struct class CharacterMSG:public FTableRowBase {
    8. GENERATED_USTRUCT_BODY()
    9. UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="CharacterMsg")
    10. FString Name;
    11. UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="CharacterMsg")
    12. float Health;
    13. UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="CharacterMsg")
    14. int32 Level;
    15. }
    16. UCLASS()
    17. class CPDD1_API UCharacterMsgObject : public UObject
    18. {
    19. GENERATED_BODY()
    20. };

    编译生成

    做一个csv表格,对应结构体的元素

     拖拽csv到UE5中

    导入时选中上述创建的结构体

    创建、实例化、结构体

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "Engine/Classes/Engine/DataTable.h"
    5. #include "UObject/NoExportTypes.h"
    6. #include "CharacterMsgObject.generated.h"
    7. USTRUCT(BlueprintType)
    8. struct FCharacterMSG :public FTableRowBase
    9. {
    10. GENERATED_USTRUCT_BODY()
    11. FCharacterMSG();//略
    12. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CharacterMsg")
    13. FString Name;
    14. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CharacterMsg")
    15. float Health;
    16. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CharacterMsg")
    17. int32 Level;
    18. };
    19. UCLASS()
    20. class CPDD1_API UCharacterMsgObject : public UObject
    21. {
    22. GENERATED_BODY()
    23. public:
    24. FCharacterMSG CMSG;//供实体类调用
    25. };
    1. //创建实例
    2. UCharacterMsgObject* MyTestMSGObject;
    1. MyTestMSGObject = NewObject(GetWorld(), UCharacterMsgObject::StaticClass());
    2. if (MyTestMSGObject) {
    3. UE_LOG(LogTemp, Warning, TEXT("MyObject is %s"), *MyTestMSGObject->GetName());
    4. UE_LOG(LogTemp, Warning, TEXT("NAME is %s"), *MyTestMSGObject->CMSG.Name);
    5. UE_LOG(LogTemp, Warning, TEXT("HEALTH is %f"), MyTestMSGObject->CMSG.Health);
    6. UE_LOG(LogTemp, Warning, TEXT("LEVEL is %d"), MyTestMSGObject->CMSG.Level);
    7. }

    GameInstance

    1. UMyGameInstance* MyGameInstance;
    2. MyGameInstance = Cast(GetWorld()->GetFirstPlayerController()->GetGameInstance());

    应用游戏实例类 

    Actor

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "Components/SceneComponent.h"
    5. #include "Components/StaticMeshComponent.h"
    6. #include "Components/BoxComponent.h"
    7. #include "Particles/ParticleSystemComponent.h"
    8. #include "Components/AudioComponent.h"
    9. #include "GameFramework/Actor.h"
    10. #include "MyActor.generated.h"
    11. UCLASS()
    12. class CPDD1_API AMyActor : public AActor
    13. {
    14. GENERATED_BODY()
    15. public:
    16. // Sets default values for this actor's properties
    17. AMyActor();
    18. protected:
    19. // Called when the game starts or when spawned
    20. virtual void BeginPlay() override;
    21. public:
    22. // Called every frame
    23. virtual void Tick(float DeltaTime) override;
    24. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    25. class USceneComponent* MyScene;
    26. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    27. class UStaticMeshComponent* MyMesh;
    28. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    29. class UParticleSystemComponent* MyParticle;
    30. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    31. class UBoxComponent* MyBox;
    32. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    33. class UAudioComponent* MyAudio;
    34. };
    1. AMyActor::AMyActor()
    2. {
    3. // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
    4. PrimaryActorTick.bCanEverTick = true;
    5. MyScene = CreateDefaultSubobject(TEXT("MyCustomScene"));
    6. MyMesh = CreateDefaultSubobject(TEXT("MyCustomScene"));
    7. MyParticle = CreateDefaultSubobject(TEXT("MyCustomParticleSystem"));
    8. MyBox = CreateDefaultSubobject(TEXT("MyCustomBox"));
    9. MyAudio = CreateDefaultSubobject(TEXT("MyCustomAudio"));
    10. RootComponent = MyScene;
    11. MyMesh->SetupAttachment(MyScene);
    12. MyParticle->SetupAttachment(MyScene);
    13. MyBox->SetupAttachment(MyScene);
    14. MyAudio->SetupAttachment(MyBox);
    15. }

    静态加载类,要加   “_C”

    camera

    1. UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="MySceneComponent")
    2. USceneComponent* MyRoot;
    3. UPROPERTY(VisibleAnywhere,BlueprintReadOnly,Category="MySceneComponent")
    4. USpringArmComponent* MySpringArm;
    5. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "MySceneComponent")
    6. UCameraComponent* MyCamera;
    1. // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
    2. PrimaryActorTick.bCanEverTick = true;
    3. MyRoot = CreateDefaultSubobject(TEXT("MyRoot"));
    4. MySpringArm = CreateDefaultSubobject(TEXT("MySpringArm"));
    5. MyCamera = CreateDefaultSubobject(TEXT("MyCamera"));
    6. RootComponent = MyRoot;
    7. MySpringArm->SetupAttachment(MyRoot);
    8. MyCamera->SetupAttachment(MySpringArm);
    9. MySpringArm->bDoCollisionTest = false;

    绑定滚轮控制摇臂移动

    1. #include "CoreMinimal.h"
    2. #include "GameFramework/PlayerController.h"
    3. #include "SPlayerController.generated.h"
    4. /**
    5. *
    6. */
    7. UCLASS()
    8. class CPDD1_API ASPlayerController : public APlayerController
    9. {
    10. GENERATED_BODY()
    11. public:
    12. virtual void SetupInputComponent();
    13. void WheelUpFunction();
    14. void WheelDownFunction();
    15. };

     绑定键在UE5输入中设置

    因为这里的Pawn和Controller都设置为当前gamemode的角色,所有getPawn会锁到当前操控者的Pawn。

    1. #include "SPlayerController.h"
    2. #include "MyPawn.h"
    3. void ASPlayerController::SetupInputComponent()
    4. {
    5. Super::SetupInputComponent();
    6. InputComponent->BindAction("WheelUp", IE_Pressed, this, &ASPlayerController::WheelUpFunction);
    7. InputComponent->BindAction("WheelDown", IE_Pressed, this, &ASPlayerController::WheelDownFunction);
    8. }
    9. void ASPlayerController::WheelUpFunction()
    10. {
    11. if (GetPawn()) {
    12. AMyPawn* pawn1= Cast(GetPawn());
    13. pawn1->Zoom(1,1);
    14. }
    15. }
    16. void ASPlayerController::WheelDownFunction()
    17. {
    18. if (GetPawn()) {
    19. AMyPawn* pawn1 = Cast(GetPawn());
    20. pawn1->Zoom(-1, 1);
    21. }
    22. }
    1. void AMyPawn::Zoom(float Direction, float Speed)
    2. {
    3. float temp = MySpringArm->TargetArmLength - Direction * Speed * 10;
    4. if (temp > 2000.f || temp < 500.f)
    5. MySpringArm->TargetArmLength = temp;
    6. }

     

    碰撞绑定

    1. UPROPERTY(VisibleAnywhere,BlueprintReadWrite,Category="MySceneComponent")
    2. class UBoxComponent* MyBox;
    1. MyBox->OnComponentBeginOverlap.AddDynamic(this, &AMyActor::BeginOverlapFunction);
    2. MyBox->OnComponentEndOverlap.AddDynamic(this, &AMyActor::EndOverlapFunction);
    3. MyBox->OnComponentHit.AddDynamic(this, &AMyActor::OnComponentHitFunction);

    绑定函数的参数从何而来?

     

    -转到定义

    再转到定义

    找到同义的参数,看数字,如果是six,就把该函数后6位复制过来,绑定函数的参数括号内,去掉定义类型和变量名之间的逗号即可。

    1. UFUNCTION()
    2. void BeginOverlapFunction(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
    3. UFUNCTION()
    4. void EndOverlapFunction(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
    5. UFUNCTION()
    6. void OnComponentHitFunction(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);

    角色碰撞设定 

    1. //碰撞设置
    2. MyBox->SetCollisionEnabled(ECollisionEnabled::NoCollision);
    3. MyBox->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
    4. MyBox->SetCollisionEnabled(ECollisionEnabled::PhysicsOnly);
    5. MyBox->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
    6. MyBox->SetCollisionEnabled(ECollisionEnabled::ProbeOnly);
    7. MyBox->SetCollisionEnabled(ECollisionEnabled::QueryAndProbe);
    8. //碰撞对象类型
    9. MyBox->SetCollisionObjectType(ECC_WorldDynamic);
    10. MyBox->SetCollisionObjectType(ECC_WorldStatic);
    11. MyBox->SetCollisionObjectType(ECC_Pawn);
    12. MyBox->SetCollisionObjectType(ECC_PhysicsBody);
    13. MyBox->SetCollisionObjectType(ECC_Vehicle);
    14. MyBox->SetCollisionObjectType(ECC_Destructible);
    15. //碰撞响应
    16. MyBox->SetCollisionResponseToAllChannels(ECR_Block);
    17. MyBox->SetCollisionResponseToAllChannels(ECR_Overlap);
    18. MyBox->SetCollisionResponseToAllChannels(ECR_Ignore);
    19. MyBox->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);//pawn允许重叠
    20. MyBox->SetCollisionResponseToChannel(ECC_WorldStatic,ECR_Block);//世界静态阻挡
    21. MyBox->SetCollisionResponseToChannel(ECC_WorldDynamic,ECR_Ignore);//世界动态忽略
    22. MyBox->SetBoxExtent(FVector(64, 64, 64));

    按钮

    绑定事件绑定函数时不用加括号

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "Components/Button.h"
    5. #include "Blueprint/UserWidget.h"
    6. #include "MyUserWidget.generated.h"
    7. UCLASS()
    8. class CPDD1_API UMyUserWidget : public UUserWidget
    9. {
    10. GENERATED_BODY()
    11. public:
    12. UPROPERTY(meta=(BindWidget))//UI控件创建的按钮名称和声明名称相同
    13. UButton *ButtonStart;
    14. UPROPERTY(meta=(BindWidget))
    15. UButton* ButtonQuit;
    16. UFUNCTION()
    17. void Start();
    18. UFUNCTION()
    19. void Quit();
    20. virtual bool Initialize()override;//重写组件初始化函数
    21. UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="MyHealth")
    22. float CurrentHealth=100.f;
    23. UPROPERTY(EditAnywhere,BlueprintReadWrite,Category="MyHealth")
    24. float MaxHealth = 100.f;
    25. UFUNCTION()
    26. void UpdateHealth();
    27. };
    1. #include "MyUserWidget.h"
    2. bool UMyUserWidget::Initialize()
    3. {
    4. if(!Super::Initialize())
    5. return false;
    6. ButtonStart->OnClicked.AddDynamic(this, &UMyUserWidget::Start);
    7. ButtonQuit->OnClicked.AddDynamic(this,&UMyUserWidget::Quit);
    8. return true;
    9. }
    10. void UMyUserWidget::UpdateHealth()
    11. {
    12. if (CurrentHealth <= 0) {
    13. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Death"));
    14. }
    15. else {
    16. CurrentHealth -= 30;
    17. }
    18. }
    19. void UMyUserWidget::Start()
    20. {
    21. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Start"));
    22. UpdateHealth();
    23. }
    24. void UMyUserWidget::Quit()
    25. {
    26. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Quit"));
    27. }

    UI显示 

    在游戏模式的控制器脚本的开始运行函数中,

    根据资源路径加载类,并创建该类的实例作为“提升为变量”的接盘。

    1. void ASPlayerController::BeginPlay()
    2. {
    3. Super::BeginPlay();
    4. UClass* widgetClass = LoadClass(NULL, TEXT("/Script/UMGEditor.WidgetBlueprint'/Game/HbtScripts/MyUserWidget233.MyUserWidget233_C'"));
    5. UMyUserWidget* MyWidget = nullptr;
    6. MyWidget = CreateWidget(GetWorld(), widgetClass);
    7. MyWidget->AddToViewport();
    8. }

    单播代理

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "GameFramework/Actor.h"
    5. #include "MyDelegateActor.generated.h"
    6. DECLARE_DELEGATE(NoParamDelegate);//1.声明代理类型
    7. DECLARE_DELEGATE_OneParam(OneParamDelegate,FString);
    8. DECLARE_DELEGATE_TwoParams(TwoParamDelegate, FString, int32);
    9. DECLARE_DELEGATE_ThreeParams(ThreeParamDelegate, FString, int32, float);
    10. DECLARE_DELEGATE_RetVal(FString, RetvalDelegate);
    11. UCLASS()
    12. class CPDD1_API AMyDelegateActor : public AActor
    13. {
    14. GENERATED_BODY()
    15. public:
    16. // Sets default values for this actor's properties
    17. AMyDelegateActor();
    18. protected:
    19. // Called when the game starts or when spawned
    20. virtual void BeginPlay() override;
    21. public:
    22. // Called every frame
    23. virtual void Tick(float DeltaTime) override;
    24. //2.声明代理名称
    25. NoParamDelegate NoParamDelegate;
    26. OneParamDelegate OneParamDelegate;
    27. TwoParamDelegate TwoParamDelegate;
    28. ThreeParamDelegate ThreeParamDelegate;
    29. RetvalDelegate RetvalDelegate;
    30. //声明代理函数
    31. void NoParamFunction();
    32. void OneParamFunction(FString str);
    33. void TwoParamFunction(FString str,int32 value);
    34. void ThreeParamFunction(FString str,int32 value,float balue1);
    35. FString RetvalFunction();
    36. };

     

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #include "MyDelegateActor.h"
    3. // Sets default values
    4. AMyDelegateActor::AMyDelegateActor()
    5. {
    6. // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
    7. PrimaryActorTick.bCanEverTick = true;
    8. //3.绑定代理方法
    9. NoParamDelegate.BindUObject(this, &AMyDelegateActor::NoParamFunction);
    10. OneParamDelegate.BindUObject(this, &AMyDelegateActor::OneParamFunction);
    11. TwoParamDelegate.BindUObject(this, &AMyDelegateActor::TwoParamFunction);
    12. ThreeParamDelegate.BindUObject(this, &AMyDelegateActor::ThreeParamFunction);
    13. RetvalDelegate.BindUObject(this, &AMyDelegateActor::RetvalFunction);
    14. }
    15. // Called when the game starts or when spawned
    16. void AMyDelegateActor::BeginPlay()
    17. {
    18. Super::BeginPlay();
    19. //4.调用代理
    20. NoParamDelegate.ExecuteIfBound();
    21. OneParamDelegate.ExecuteIfBound("OneParamDelegate");
    22. TwoParamDelegate.ExecuteIfBound("TwoParamDelegate",648);
    23. ThreeParamDelegate.ExecuteIfBound("ThreeParamDelegate",648,3.6f);
    24. FString strvalue= RetvalDelegate.Execute();
    25. }
    26. // Called every frame
    27. void AMyDelegateActor::Tick(float DeltaTime)
    28. {
    29. Super::Tick(DeltaTime);
    30. }
    31. void AMyDelegateActor::NoParamFunction()
    32. {
    33. GEngine->AddOnScreenDebugMessage(-1,5.0f,FColor::Blue,TEXT("NoParamDelegate"));
    34. }
    35. void AMyDelegateActor::OneParamFunction(FString str)
    36. {
    37. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Blue, FString::Printf(TEXT("%s"),*str));
    38. }
    39. void AMyDelegateActor::TwoParamFunction(FString str, int32 value)
    40. {
    41. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Blue, FString::Printf(TEXT("%s,%d"), *str,value));
    42. }
    43. void AMyDelegateActor::ThreeParamFunction(FString str, int32 value, float value1)
    44. {
    45. GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Blue, FString::Printf(TEXT("%s,%d,%f"), *str, value, value1));
    46. }
    47. FString AMyDelegateActor::RetvalFunction()
    48. {
    49. FString str = FString::Printf(TEXT("RetvalFunction"));
    50. return str;
    51. }

    多播和动态多播

    声明类型

    1. DECLARE_MULTICAST_DELEGATE_OneParam(OneParamMultiDelegate, FString);
    2. DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FDynamicMutilDelegate,FString,param);

    声明名称

    1. //多播代理
    2. OneParamMultiDelegate OneParamMultiDelegate;
    3. //动态多播
    4. UPROPERTY(BlueprintAssignable)
    5. FDynamicMutilDelegate FDynamicMutilDelegate;

     绑定方法

    1. //多播代理绑定
    2. OneParamMultiDelegate.AddUObject(this, &AMyDelegateActor::MultiDelegateFunction1);

    执行(参数根据自己定义的类型) 

    1. //执行多播代理
    2. OneParamMultiDelegate.Broadcast("OneParamMultiDelegate");
    3. //执行动态多播代理
    4. FDynamicMutilDelegate.Broadcast("FDynamicMutilDelegate");

    多播代理能同时调用多个函数,区别是动态多播能暴露给蓝图。

    多播在脚本中写好绑定的多播函数。

    动态多播在此基础上,能在蓝图上额外绑定事件,不止函数。

    写一个接口

    用I开头那个

    声明要重写函数时,有{}

    1. // Fill out your copyright notice in the Description page of Project Settings.
    2. #pragma once
    3. #include "CoreMinimal.h"
    4. #include "UObject/Interface.h"
    5. #include "TestInterface.generated.h"
    6. // This class does not need to be modified.
    7. UINTERFACE(MinimalAPI)
    8. class UTestInterface : public UInterface
    9. {
    10. GENERATED_BODY()
    11. };
    12. /**
    13. *
    14. */
    15. class CPDD1_API ITestInterface
    16. {
    17. GENERATED_BODY()
    18. // Add interface functions to this class. This is the class that will be inherited to implement this interface.
    19. public:
    20. virtual void Attack() {};
    21. virtual void CaclulateHealth() {};
    22. };

     调用,接屁股+头文件

    重写

    1. virtual void Attack() override;
    2. virtual void CaclulateHealth() override;

     然后再cpp编写即可。

    其他

    在使用打印语句时报错什么断点问题点,尝试在打印语句上加UFUNCTION

    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("Death"));

    变量要编辑,组件要可视,然后均为蓝图读写

     NewObject 和 CreateDefaultSubobject区别

    NewObject 和 CreateDefaultSubobject 是 Unreal Engine 中用于创建对象的两种不同方式,它们有以下区别:

    1. 对象类型:NewObject 可以用于创建任何类型的对象,包括 UObject、AActor、APawn 等。而 CreateDefaultSubobject 仅适用于在一个类的构造函数或初始化过程中创建默认的子对象。

    2. 对象生命周期:使用 NewObject 创建的对象是动态分配的,并由开发人员负责管理其生命周期。而使用 CreateDefaultSubobject 创建的对象是由 Unreal Engine 的对象系统自动管理的,它们的生命周期与宿主对象的生命周期相同。

    3. 对象属性:CreateDefaultSubobject 创建的对象会自动继承宿主对象的属性设置,例如编辑器中设置的默认值、蓝图可编辑性等。而使用 NewObject 创建的对象需要手动设置属性。

    4. 宿主对象关系:CreateDefaultSubobject 创建的子对象与宿主对象之间建立了父子关系,这意味着子对象的生命周期与宿主对象紧密相关,并且在宿主对象销毁时,子对象也会被销毁。而 NewObject 创建的对象没有默认的宿主对象关系。

  • 相关阅读:
    开机启动流程及营救模式
    TimescaleDB 开源时序数据库
    分享一份关于 Rust 编程的学习指南
    全志A33使用主线U-Boot方法
    C语言实现DNS请求器
    计算机单位、变量、数据类型、类型转换、转义字符
    (王道考研计算机网络)第四章网络层-第二节:路由算法与路由协议概述
    抖音短视频矩阵系统搭建
    嵌入式系统开发【深入浅出】 IWDG 与 WWDG
    前端培训丁鹿学堂:每天五分钟,轻松入门vue3(三)
  • 原文地址:https://blog.csdn.net/weixin_56537692/article/details/134378982