CS/졸업 프로젝트(Duk to Me)
PlayFab과 Unity 연동 (4) - 게임 점수 Data 보내고 가져오기
letthegamesbegin7
2023. 9. 18. 21:41
반응형
지난 단계에 닉네임 Data를 계정별로 보낸 것과 같이 Unity 내에서 게임을 끝까지 마쳤을 때 저장되는 점수 Data를 PlayFab으로 보내고 가져오는 기능을 구현해보자.
① 'ScoreManager.cs'는 영어회화 학습을 진행하는 여러 개의 Scene으로 부터 인식된 음성인식을 미리 지정된 Script Text File과 대조하여 나온 점수 정보를 관리하는 C# Script이다. 이 Script에서 최종적으로 나온 점수 Data를 PlayFab으로 보내는 동작을 정의하는 'SendScoreToPlayFab()'를 추가하여 수정하기 (이때 점수 Data는 Dictionary Type으로 보냄)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour
{
public Text t_score, t_average;
public static int totalScore = 0;
public static void AddScore(int score)
{
totalScore += score;
}
public static int GetScore()
{
return totalScore / 6; // 씬의 갯수만큼 나눠서 평균 출력하기
}
// SendScoreToPlayFab() method를 call
public void HandleButtonClick()
{
int scoreValue = ScoreManager.GetScore();
if (scoreValue <= 100 && scoreValue >= 80)
{
t_score.text="Excellent!";
t_average.text=$"Average Score: {scoreValue}%";
//Debug.Log("Excellent!");
//Debug.Log($"Average Score: {scoreValue}%");
}
else if (scoreValue >= 70)
{
t_score.text="Great job!";
t_average.text=$"Average Score: {scoreValue}%";
//Debug.Log("Great job!");
//Debug.Log($"Average Score: {scoreValue}%");
}
else if (scoreValue >= 50)
{
t_score.text="Well done!";
t_average.text=$"Average Score: {scoreValue}%";
//Debug.Log("Well done!");
//Debug.Log($"Average Score: {scoreValue}%");
}
else if (scoreValue >= 0)
{
t_score.text="Keep Practicing!";
t_average.text=$"Average Scor: {scoreValue}%";
//Debug.Log("Keep Practicing!");
//Debug.Log($"Average Scor: {scoreValue}%");
}
// Call the method to send the score to PlayFab
SendScoreToPlayFab(scoreValue);
}
// Call받으면 PlayFab DB로 score를 account별로 보내기
private void SendScoreToPlayFab(int score)
{
// Assuming you have already authenticated the player with PlayFab
// Create a request to update the player's data
UpdateUserDataRequest request = new UpdateUserDataRequest
{
Data = new Dictionary<string, string>
{
{ "score", score.ToString() }
}
};
// Send the request to PlayFab
PlayFabClientAPI.UpdateUserData(request, OnUpdateUserDataSuccess, OnUpdateUserDataFailure);
}
private void OnUpdateUserDataSuccess(UpdateUserDataResult result)
{
Debug.Log("Score successfully sent to PlayFab!");
}
private void OnUpdateUserDataFailure(PlayFabError error)
{
Debug.LogError("Failed to send score to PlayFab: " + error.ErrorMessage);
}
}
② 이제 점수 Data를 가져올 'My Page' Scene에 적용되는 'nick_mypage.cs' Script를 점수 Data를 가져오는 Method인 'FetchScoreFromPlayFab()' 등을 추가하여 수정하기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using PlayFab;
using PlayFab.ClientModels;
using UnityEngine.UI;
public class nick_mypage : MonoBehaviour
{
public TMPro.TextMeshProUGUI t_name, t_score1;
public void Start()
{
// Fetch and display PlayFab data when transitioning scenes
FetchDataFromPlayFab();
}
// 닉네임 Data 불러오기
private void FetchDataFromPlayFab()
{
// Request to get the player's account info
GetAccountInfoRequest request = new GetAccountInfoRequest();
// Send the request to PlayFab
PlayFabClientAPI.GetAccountInfo(request, OnGetAccountInfoSuccess, OnGetAccountInfoFailure);
}
private void OnGetAccountInfoSuccess(GetAccountInfoResult result)
{
// Fetch and display user's display name
string displayName = result.AccountInfo.TitleInfo.DisplayName;
//Debug.Log("Fetched Display Name: " + displayName);
t_name.text = displayName;
// Fetch and display user's score
FetchScoreFromPlayFab();
}
private void OnGetAccountInfoFailure(PlayFabError error)
{
Debug.LogError("Failed to fetch PlayFab account info: " + error.ErrorMessage);
}
// 점수 Data 불러오기
private void FetchScoreFromPlayFab()
{
// Assuming you have already authenticated the player with PlayFab
// Create a request to get the player's data
GetUserDataRequest request = new GetUserDataRequest();
// Send the request to PlayFab
PlayFabClientAPI.GetUserData(request, OnGetUserDataSuccess, OnGetUserDataFailure);
}
private void OnGetUserDataSuccess(GetUserDataResult result)
{
if (result.Data.TryGetValue("score", out var scoreValue))
{
if (int.TryParse(scoreValue.Value, out var parsedScore))
{
// Debug.Log("Fetched Score: " + parsedScore);
t_score1.text = parsedScore.ToString();
}
else
{
Debug.LogError("Failed to parse fetched score.");
}
}
else
{
Debug.Log("No 'score' data found in PlayFab.");
}
}
private void OnGetUserDataFailure(PlayFabError error)
{
Debug.LogError("Failed to fetch PlayFab data: " + error.ErrorMessage);
}
}
여기까지 끝나면 Unity Project를 Play하여 영어회화 학습 게임을 끝까지 진행했을 때 점수 Data가 Playfab으로 보내지고, My Page에서 마지막에 실행한 게임에 대한 점수 정보를 확인할 수 있다.
점수 Data 출력결과
반응형