728x90
반응형
SMALL
#012 게시글에서 생성한 구글 스크립트는 삭제 후 새로운 스크립트로 유니티 구글 플레이 로그인 구현 및 데이터 관리를 구현해보았다.
우선, 파이어베이스 버전을 체크하여 '앱이 최신 업그레이드 버전인지' 확인하는 코드를 작성했다.
파이어베이스 서버를 통해 <앱 버전 최신여부 체크>
1. 우선, 반드시 google-services 파일이 유니티 프로젝트 창에 있어야한다. (파이어베이스에서 로그인 후 다운로드 가능)
2. 버전 체크하는 오브젝트에 VersionChecker 스크립트를 컴포넌트 하고, 관련 오브젝트를 할당했다.
3. VersionChecker 스크립트는 아래와 같이 작성했다.
using UnityEngine;
using Firebase;
using Firebase.Database;
using System;
using UnityEngine.UI;
public class VersionChecker : MonoBehaviour
{
public Text Version;
public string currentVersion; // 현재 앱의 버전 정보를 저장할 변수
private string recentVersion; // 파이어베이스에서 가져온 최신 버전 정보를 저장할 변수]
public GameObject PleaseUpdate;
public bool NeedUpdate;
void Awake()
{
// 현재 버전 확인
// PlayerSettings.bundleVersion으로 현재 앱의 버전 정보 가져오기
currentVersion = Application.version;
Debug.Log("현재 앱 버전: " + currentVersion);
Version.text = currentVersion;
// Firebase 초기화
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
if (task.Exception != null)
{
Debug.LogError("Firebase 초기화 중 오류 발생: " + task.Exception);
return;
}
// 파이어베이스 데이터베이스에서 최신 버전 정보를 읽어옴
FirebaseDatabase.DefaultInstance.GetReference("appVersion").GetValueAsync().ContinueWith(versionTask =>
{
if (versionTask.Exception != null)
{
Debug.LogError("파이어베이스에서 버전 정보를 읽어오는 중 오류 발생: " + versionTask.Exception);
return;
}
DataSnapshot snapshot = versionTask.Result;
recentVersion = snapshot.Value.ToString();
Debug.Log("새로운 버전: "+recentVersion);
// 최신 버전 정보를 가져온 후에 CheckForUpdate 메서드를 호출합니다.
CheckForUpdate();
});
});
}
private void CheckForUpdate()
{
// 현재 버전과 최신 버전을 비교하여 업데이트가 필요한지 확인
if (currentVersion != recentVersion)
{
Debug.Log("새로운 버전이 있습니다. 업데이트가 필요합니다");
// 여기에 업데이트 알림을 표시하거나 업데이트 다이얼로그를 표시하는 등의 작업을 수행할 수 있습니다.
NeedUpdate = true;
}
else
{
Debug.Log("최신 버전을 사용 중입니다");
// 여기에 어플리케이션을 진행하는 등의 작업을 수행할 수 있습니다.
NeedUpdate = false;
}
}
void FixedUpdate()
{
if (NeedUpdate)
{
PleaseUpdate.gameObject.SetActive(true);
}
}
}
4. 파이어 베이스에 가면 아래와 같이 값과 가치를 입력했다.
구글 플레이 로그인 구현 및 데이터 관리 (저장/불러오기)
기존에 #012 게시글에서 작성한 구글 플레이 로그인 구현 방법은 데이터를 관리하기에 적합하지 않다고 판단되어, 스크립트를 삭제한 후 다시 아래와 같은 스크립트를 생성하였다. 이 스크립트 하나로 구글 관련된 로그인과 데이터를 관리하기로 한다.
1. PlayCloudDataManager 스크립트 생성 및 싱글톤
2. 로그인에 성공할 경우 유저의 닉네임, 아이디와 데이터까지 불러오도록 함 (초록별, 노랑별, 빨강별)
using UnityEngine;
using System;
using System.Collections;
//gpg
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.SavedGame;
//for encoding
using System.Text;
//for extra save ui
using UnityEngine.SocialPlatforms;
//for text, remove
using UnityEngine.UI;
public class PlayCloudDataManager : MonoBehaviour
{
//싱글톤
private static PlayCloudDataManager instance;
public static PlayCloudDataManager Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<PlayCloudDataManager>();
if (instance == null)
{
instance = new GameObject("PlayGameCloudData").AddComponent<PlayCloudDataManager>();
}
}
return instance;
}
}
//싱글톤
// UI 관련
public Button Button_GameStart;
public Button Button_login; // 로그인 버튼
public Button Button_logout; // 로그아웃 버튼
public Text UserNameText; //유저 닉네임
public Text UserIDText; // 유저 아이디
public bool isProcessing //현재 데이터를 처리 중인지를 나타내는 불린 값
{
get;
private set;
}
public string loadedData //클라우드로부터 불러온 데이터를 저장
{
get;
private set;
}
private const string m_saveFileName = "game_save_data";
public bool isAuthenticated // 사용자가 인증되었는지
{
get { return Social.localUser.authenticated; }
}
// 데이터 추가원할 시 아래 int와 bool값 추가하기 ★
public int greenStarCount = 0; // 유저의 초록별
public int yellowStarCount = 0; // 유저의 노란별
public int redStarCount = 0; // 유저의 빨간별
public bool isgreenStarLoaded = false; // 데이터가 로드되었는지 여부
public bool isyellowStarLoaded = false;
public bool isredStarLoaded = false;
private void InitiatePlayGames() //Google Play Games SDK를 초기화
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
// enables saving game progress.
.EnableSavedGames()
.Build();
PlayGamesPlatform.InitializeInstance(config);
// recommended for debugging:
PlayGamesPlatform.DebugLogEnabled = false;
// Activate the Google Play Games platform
PlayGamesPlatform.Activate();
}
private void Awake() //게임이 실행될 때 Google Play Games SDK를 초기화
{
InitiatePlayGames();
}
private void Start()
{
// 사용자가 인증되어 있으면 로그아웃 버튼을 활성화
if (isAuthenticated)
{
Button_GameStart.gameObject.SetActive(true);
Button_login.gameObject.SetActive(false);
Button_logout.gameObject.SetActive(true);
}
else // 로그인 상태가 아니면
{
Button_GameStart.gameObject.SetActive(false);
Button_login.gameObject.SetActive(true);
Button_logout.gameObject.SetActive(false);
}
}
public void Login() // 사용자를 인증합니다. 사용자가 인증되지 않았을 경우에는 인증을 시도
{
Social.localUser.Authenticate((bool success) =>
{
if (!success)
{
Debug.Log("로그인 실패");
}
else
{
Button_GameStart.gameObject.SetActive(true);
Button_login.gameObject.SetActive(false);
Button_logout.gameObject.SetActive(true);
Debug.Log("로그인 성공");
Debug.Log("닉네임: " + Social.localUser.userName);
Debug.Log("아이디: " + Social.localUser.id);
// 유저 닉네임과 아이디를 표시
UserNameText.text = "닉네임: " + Social.localUser.userName;
UserIDText.text = "아이디: " + Social.localUser.id;
// 게임 데이터 불러오기
LoadGameData();
}
});
}
private void LoadGameData() // 구글 데이터로부터 데이터를 불러옵니다.
{
if (isAuthenticated)
{
isgreenStarLoaded = false; // 데이터 추가원할 시 이 부분 추가하기 ★
isyellowStarLoaded = false;
isredStarLoaded = false;
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(
m_saveFileName,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
OnFileOpenToLoad);
}
}
private void SaveGameData() // 구글 데이터에 별데이터를 저장합니다.
{
if (isAuthenticated)
{
string greenStarData = greenStarCount.ToString();
string yellowStarData = yellowStarCount.ToString();
string redStarData = redStarCount.ToString();
byte[] data = Encoding.UTF8.GetBytes(greenStarData + "," + yellowStarData + "," + redStarData);
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(
m_saveFileName,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
(status, metadata) => OnFileOpenToSave(status, metadata, data));
}
}
// 불러오기 성공 시 호출되는 콜백
private void OnFileOpenToLoad(SavedGameRequestStatus status, ISavedGameMetadata metaData)
{
if (status == SavedGameRequestStatus.Success)
{
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(metaData, OnGameLoad);
}
else
{
Debug.LogWarning("게임 데이터를 불러오는 중 오류 발생" + status);
}
}
// 저장 성공 시 호출되는 콜백
private void OnFileOpenToSave(SavedGameRequestStatus status, ISavedGameMetadata metaData, byte[] data)
{
if (status == SavedGameRequestStatus.Success)
{
SavedGameMetadataUpdate.Builder builder = new SavedGameMetadataUpdate.Builder();
SavedGameMetadataUpdate updatedMetadata = builder.Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(metaData, updatedMetadata, data, OnGameSave);
}
else
{
Debug.LogWarning("게임 데이터를 저장하는 중 오류 발생" + status);
}
}
// 데이터 로드 후 처리
private void OnGameLoad(SavedGameRequestStatus status, byte[] bytes)
{
if (status == SavedGameRequestStatus.Success)
{
string[] data = Encoding.UTF8.GetString(bytes).Split(',');
if (data.Length >= 3) // 데이터 추가원할 시 숫자 늘이기 ★
{
// 데이터 추가원할 시 아래 부분 추가하기 ★
greenStarCount = int.Parse(data[0]);
yellowStarCount = int.Parse(data[1]);
redStarCount = int.Parse(data[2]);
//GreenStarText.text = "Green Star: " + greenStarCount;
//YellowStarText.text = "Yellow Star: " + yellowStarCount;
//RedStarText.text = "Red Star: " + redStarCount;
isgreenStarLoaded = true;
isyellowStarLoaded = true;
isredStarLoaded = true;
}
}
else
{
Debug.LogWarning("게임 데이터를 불러오는 중 오류 발생" + status);
}
}
private void OnGameSave(SavedGameRequestStatus status, ISavedGameMetadata metaData) // 데이터 저장 후 처리
{
if (status != SavedGameRequestStatus.Success)
{
Debug.LogWarning("게임 데이터를 저장하는 중 오류 발생" + status);
}
}
public void AddGreenStar(int amount) // 별을 추가하고 저장합니다. // 데이터 추가원할 시 이 함수 추가하기 ★
{
greenStarCount += amount;
//GreenStarText.text = "Green Star: " + greenStarCount;
if (isgreenStarLoaded)
{
SaveGameData();
}
}
public void AddYellowStar(int amount) // 별을 추가하고 저장합니다. // 데이터 추가원할 시 이 함수 추가하기 ★
{
yellowStarCount += amount;
//YellowStarText.text = "Yellow Star: " + yellowStarCount;
if (isyellowStarLoaded)
{
SaveGameData();
}
}
public void AddRedStar(int amount) // 별을 추가하고 저장합니다. // 데이터 추가원할 시 이 함수 추가하기 ★
{
redStarCount += amount;
//RedStarText.text = "Red Star: " + redStarCount;
if (isredStarLoaded)
{
SaveGameData();
}
}
public void Logout() // 로그아웃
{
((PlayGamesPlatform)Social.Active).SignOut();
Button_logout.gameObject.SetActive(false); // 로그아웃 버튼 비활성화
}
}
728x90
반응형
LIST
'▶ SCP전쟁 개발일지' 카테고리의 다른 글
#012 유니티 구글 플레이 로그인 구현 (GPGS 로그인, 업적, 리더보드, 이벤트) (0) | 2024.04.12 |
---|---|
#문제해결 유니티 Error SignInRequest Setting result error status code to: 16 (0) | 2024.04.12 |
#문제해결 유니티 ERROR: Gradle failed to fetch dependencies (0) | 2024.04.12 |
#문제해결 유니티 ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. (0) | 2024.04.09 |
#011 파이어베이스 유니티 구현 (서버 연동, 이메일 계정 생성, 로그인, 로그아웃) (0) | 2024.04.09 |
댓글