[C++] UMG 바인딩하기

Woogle·2022년 11월 8일
0

언리얼 엔진 5

목록 보기
23/59
post-thumbnail
  • C++에서 UMG에 바인딩한 변수를 변경하여 화면에 띄워보았다.
  • Score : Bullet이 Enemy와 충돌 시 1씩 증가하는 변수

📄 Build.cs

✏️ C#

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[] {  });
	}
}
  • Build.cs 파일에서 UMG 모듈을 추가한다.

📄 Widget

✏️ Blueprint

  • 위젯 블루프린트에서 Text를 추가한다.

✏️ C++

#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 지정자로 에디터와 연동시켜준다.


📄 Game Mode

✏️ Blueprint

✏️ C++

헤더 파일

#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로 바꿔서 넣어줌.
}
  • Game Mode에서 위젯을 생성하고, 플레이어 화면에 띄워준다.
    (굳이 Game Mode가 아니라 Player Controller, Player Pawn 등에서 해도 상관없음)

📄 Bullet

✏️ C++

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);
	}
}
  • Bullet이 Enemy와 Overlap되면 Game Mode의 AddScore 함수를 호출한다.

📄 결과

  • Bullet이 Enemy와 충돌 시 Score가 1씩 증가하는 UI를 확인할 수 있다.
profile
노력하는 게임 개발자

0개의 댓글