Today, I will

[Unreal] UI Change Control 본문

Unreal

[Unreal] UI Change Control

Lv.Forest 2023. 10. 27. 10:47

언리얼에서 게임 상황에 따라서 viewport 다른 UI가 보여질 수 있도록 ui change 기능을 구현해보도록 한다.

(1) score이 보여지는 화면

(2) Enemy한테 닿아 Game Over 화면

게임모드에서 UI들을 들고 있고 다른 액터 클래스들에서 게임모드의 함수들을 불러 결국 게임모드 안에서 UI를 change하도록 짤 수 있다.

 

게임모드베이스.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "ShootingGameModeBase.generated.h"

/**
 * 
 */
UCLASS()
class GIT_TEMP_API AShootingGameModeBase : public AGameModeBase
{
	GENERATED_BODY()
public:

	UFUNCTION(BlueprintCallable, Category ="UMG_Game")
	void ChangeMenuWidget(TSubclassOf<UUserWidget> NewWidgetClass);

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "UMG_Game")
	int CurrentScore;

	UFUNCTION(BlueprintCallable, Category = "UMG_Game")
	void AddScore(int score);

	UFUNCTION(BlueprintCallable, Category = "UMG_Game")
	void GameOver();

protected:
	virtual void BeginPlay() override;
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="UMG_Game")
	TSubclassOf<UUserWidget> StartingWidgeteClass;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "UMG_Game")
	TSubclassOf<UUserWidget> GameEndWidgeteClass;

	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "UMG_Game")
	UUserWidget* CurrentWidget;
};

미리 위젯 블루프린트를 제작해두었다.

게임모드 베이스의 umg위젯 카테고리에 적절한 ui를 넣어준다.

게임모드 베이스.cpp

// Fill out your copyright notice in the Description page of Project Settings.


#include "ShootingGameModeBase.h"
#include <Blueprint/UserWidget.h>

void AShootingGameModeBase::AddScore(int score)
{
	CurrentScore += score;
}

void AShootingGameModeBase::BeginPlay()
{
	Super::BeginPlay();
	ChangeMenuWidget(StartingWidgeteClass);
}

void AShootingGameModeBase::GameOver()
{
	ChangeMenuWidget(GameEndWidgeteClass);
}

void AShootingGameModeBase::ChangeMenuWidget(TSubclassOf<UUserWidget> NewWidgetClass)
{
	if (CurrentWidget!= nullptr) {
		CurrentWidget->RemoveFromViewport();
		CurrentWidget = nullptr;
	}
	if (NewWidgetClass != nullptr)
	{
		CurrentWidget = CreateWidget(GetWorld(), NewWidgetClass);
		if (CurrentWidget!=nullptr) {
			CurrentWidget->AddToViewport();
		}
	}
}