using UnrealBuildTool; public class MyShootingCpp : ModuleRules { public MyShootingCpp(ReadOnlyTargetRules Target) : base(Target) { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; // 여기에 UMG 모듈을 추가한다. PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG" }); PrivateDependencyModuleNames.AddRange(new string[] { }); } }
#pragma once #include "CoreMinimal.h" #include "Blueprint/UserWidget.h" #include "ScoreWidget.generated.h" UCLASS() class MYSHOOTINGCPP_API UScoreWidget : public UUserWidget { GENERATED_BODY() public: UPROPERTY(EditAnywhere, meta = (BindWidget)) class UTextBlock* TextBlock_ScoreTitle; UPROPERTY(EditAnywhere, meta = (BindWidget)) class UTextBlock* TextBlock_Score; };
C++에서 UserWidget 클래스를 생성한다.
WBP에서와 같은 이름의 UTextBlock를 선언하고, UPROPERTY 지정자로 에디터와 연동시켜준다.
#pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "MyShootingCppGameModeBase.generated.h" UCLASS() class MYSHOOTINGCPP_API AMyShootingCppGameModeBase : public AGameModeBase { GENERATED_BODY() protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: int score = 0; void AddScore(int value); UPROPERTY(EditAnywhere) // 블루프린트 Details 탭에 노출시켜 지정할 수 있게 TSubclassOf<class UScoreWidget> scoreWidgetFactory; // 생성할 위젯의 설계도 class UScoreWidget* scoreWidget; // 위젯을 담는 그릇 };
#include "MyShootingCppGameModeBase.h" #include <Blueprint/UserWidget.h> #include "ScoreWidget.h" #include <Components/TextBlock.h> void AMyShootingCppGameModeBase::BeginPlay() { // Score 위젯을 생성한다. scoreWidget = CreateWidget<UScoreWidget>(GetWorld(), scoreWidgetFactory); // Score 위젯을 화면에 띄운다. scoreWidget->AddToViewport(); } void AMyShootingCppGameModeBase::AddScore(int value) { // 점수를 누적한다. score = score + value; // UI에 점수를 반영한다. scoreWidget->TextBlock_Score->SetText(FText::AsNumber(score)); // int를 FText로 바꿔서 넣어줌. }
void ABullet::OnMyComponentBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { // Overlap한 액터가 AEnemy 클래스면 실행 if (OtherActor->IsA(AEnemy::StaticClass())) { OtherActor->Destroy(); this->Destroy(); auto enemy = Cast<AEnemy>(OtherActor); enemy->Explode(); this->Destroy(); // 점수 증가 auto gameMode = Cast<AMyShootingCppGameModeBase>(GetWorld()->GetAuthGameMode()); gameMode->AddScore(1); } }