-
Unreal Engine Firebase 사용기Unreal Engine 2024. 12. 16. 20:40
<목표>
Firebase를 통해 언리얼 엔진으로 만든 게임에 로그인, 점수 기록, 점수 조회 기능을 추가한다.
Firebase 준비
1. Firebase 프로젝트 만들기
2. Firbase Authentication(로그인) 기능, Realtime Database 기능 활성화
3. API 키, Realtime Database URL, 인증 정보 준비 (API 키는 프로젝트 설정에 있음)
Unreal 준비
1. Build.cs 파일 HTTP 모듈 추가
PublicDependencyModuleNames.AddRange(new string[] { "HTTP", "Json", "JsonUtilities" });
2. 로그인 위젯 생성
3. FirebaseHelper 클래스 생성
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "FirebaseHelper.generated.h" /** * */ UCLASS() class FIREBASEPRACTICE_API UFirebaseHelper : public UObject { GENERATED_BODY() public: // 로그인 함수 static void AuthenticateWithFirebase(const FString& Email, const FString& Password, TFunction<void(FString)> OnSuccess, TFunction<void(FString)> OnError); // 데이터 저장 함수 static void SavePlayerScore(const FString& PlayerID, int32 Score, const FString& IDToken, TFunction<void()> OnSuccess, TFunction<void(FString)> OnError); // 데이터 읽기 함수 static void GetScores(const FString& IDToken, TFunction<void(TMap<FString, int32>)> OnSuccess, TFunction<void(FString)> OnError); };
#include "FirebaseHelper.h" #include "HttpModule.h" #include "Interfaces/IHttpResponse.h" void UFirebaseHelper::AuthenticateWithFirebase(const FString& Email, const FString& Password, TFunction<void(FString)> OnSuccess, TFunction<void(FString)> OnError) { TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest(); Request->SetURL(TEXT("https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=내 웹 API Key")); Request->SetVerb(TEXT("POST")); Request->SetHeader(TEXT("Content-Type"), TEXT("application/json")); FString Payload = FString::Printf(TEXT("{\"email\":\"%s\", \"password\":\"%s\", \"returnSecureToken\":true}"), *Email, *Password); Request->SetContentAsString(Payload); Request->OnProcessRequestComplete().BindLambda([OnSuccess, OnError](FHttpRequestPtr, const FHttpResponsePtr& Response, const bool bWasSuccessful) { if (bWasSuccessful && Response->GetResponseCode() == 200) { TSharedPtr<FJsonObject> JsonObject; TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString()); if (FJsonSerializer::Deserialize(Reader, JsonObject)) { const FString IdToken = JsonObject->GetStringField(TEXT("idToken")); OnSuccess(IdToken); return; } } OnError(Response->GetContentAsString()); }); Request->ProcessRequest(); } void UFirebaseHelper::SavePlayerScore(const FString& PlayerID, const int32 Score, const FString& IDToken, TFunction<void()> OnSuccess, TFunction<void(FString)> OnError) { TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest(); Request->SetURL(FString::Printf(TEXT("https://나의 firebase 주소/scores/%s.json?auth=%s"), *PlayerID, *IDToken)); Request->SetVerb(TEXT("PUT")); Request->SetHeader(TEXT("Content-Type"), TEXT("application/json")); FString Payload = FString::Printf(TEXT("{\"score\":%d}"), Score); Request->SetContentAsString(Payload); Request->OnProcessRequestComplete().BindLambda([OnSuccess, OnError](FHttpRequestPtr, const FHttpResponsePtr& Response, bool bWasSuccessful) { if (bWasSuccessful && Response->GetResponseCode() == 200) { OnSuccess(); } else { OnError(Response->GetContentAsString()); } }); Request->ProcessRequest(); } void UFirebaseHelper::GetScores(const FString& IDToken, TFunction<void(TMap<FString, int32>)> OnSuccess, TFunction<void(FString)> OnError) { TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest(); Request->SetURL(FString::Printf(TEXT("https://나의 firebase 주소/scores.json?auth=%s"), *IDToken)); Request->SetVerb(TEXT("GET")); Request->OnProcessRequestComplete().BindLambda([OnSuccess, OnError](FHttpRequestPtr, const FHttpResponsePtr& Response, bool bWasSuccessful) { if (bWasSuccessful && Response->GetResponseCode() == 200) { TSharedPtr<FJsonObject> JsonObject; TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString()); if (FJsonSerializer::Deserialize(Reader, JsonObject)) { TMap<FString, int32> Scores; for (const auto& Pair : JsonObject->Values) { FString PlayerID = Pair.Key; int32 Score = JsonObject->GetIntegerField(TEXT("score")); Scores.Add(PlayerID, Score); } OnSuccess(Scores); return; } } OnError(Response->GetContentAsString()); }); Request->ProcessRequest(); }
1. 로그인 성공
2. 점수 삽입 성공
'Unreal Engine' 카테고리의 다른 글
SkeletalMeshComponent에서 Skeleton 얻기 (0) 2024.07.01 Unreal Engine5 AI가 NavMeshVolume을 벗어나는 문제 (0) 2024.05.15 Unreal Engine5 LNK 외부 참조 에러 대부분 이걸로 해결 (0) 2024.05.09 Gameplay Ability System (0) 2024.04.30 온라인 서브시스템과 세션 생성, 찾기 (0) 2024.04.29