[C++] 게임 저장하기

Woogle·2022년 11월 10일
0

언리얼 엔진 5

목록 보기
25/59
  • 저장하기: SaveGame 클래스로 Instance를 만들어 Slot에 정보를 저장한다
  • 불러오기: 저장한 Instance를 불러온다.
  • SaveGame: 저장하고자 하는 정보를 담는 오브젝트

📄 Save Game

✏️ 헤더

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "MyShootingSaveGame.generated.h"

UCLASS()
class MYSHOOTINGCPP_API UMyShootingSaveGame : public USaveGame
{
	GENERATED_BODY()

public:
	UPROPERTY()				// 지정자 있어야 저장 가능
	int32 save_highScore;	// 저장 정보
};

📄 Game Mode

✏️ 헤더

public:
	AMyShootingCppGameModeBase();	// 생성자

public:
	FString saveFileName;
	int32 saveUserIndex;

	void DoSaveGame(int32 score);	// highScore 값이 변하면 호출
	int32 DoLoadGame();				// 게임을 시작할 때 호출

✏️ 소스

AMyShootingCppGameModeBase::AMyShootingCppGameModeBase()
{
	// 생성자에서 변수 초기화
	saveFileName = TEXT("HIGH_SCORE");
	saveUserIndex = 0;
}

void AMyShootingCppGameModeBase::BeginPlay()
{
	Super::BeginPlay();

	// 저장된 세이브 파일을 불러온다
	highScore = DoLoadGame();
    // 위젯에 highScore를 반영한다
	scoreWidget->TextBlock_HighScore->SetText(FText::AsNumber(highScore));
}

void AMyShootingCppGameModeBase::DoSaveGame(int32 value)
{
	USaveGame* temp = UGameplayStatics::CreateSaveGameObject(UMyShootingSaveGame::StaticClass());	// 인스턴스 생성
	UMyShootingSaveGame* saveInst = Cast<UMyShootingSaveGame>(temp);	// USaveGame* 타입을 UMyShootingSaveGame*로 형변환
	saveInst->save_highScore = value;	// 인스턴스 안에 저장할 값을 넣어준다
	UGameplayStatics::SaveGameToSlot(saveInst, saveFileName, saveUserIndex);
}

int32 AMyShootingCppGameModeBase::DoLoadGame()
{
	// 저장 파일이 없다면
	if (UGameplayStatics::DoesSaveGameExist(saveFileName, saveUserIndex) == false)
	{
		return 0;
	}
	// 저장 파일이 있다면
	USaveGame* temp = UGameplayStatics::LoadGameFromSlot(saveFileName, saveUserIndex);	// SaveGame 클래스를 불러온다
	UMyShootingSaveGame* saveInst = Cast<UMyShootingSaveGame>(temp);					// UMyShootingSave 형식으로 변환한다
	return saveInst->save_highScore;
}


📄 참고자료

profile
노력하는 게임 개발자

0개의 댓글