유니티 플레이팹 Json으로 타이틀 데이터 저장, 불러오기 Playfab
플레이팹 로그인이 되었다는 가정하에 진행
유니티 플레이팹 게스트 로그인 Playfab Sign In with Guest Login 간단 사용법
코드 작성 using PlayFab; using PlayFab.ClientModels; using PlayFab.Json; using PlayFab.ProfilesModels; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using EntityKey = PlayFab.ProfilesMod
parksh3641.tistory.com
공통
private void DisplayPlayfabError(PlayFabError error) => Debug.LogError("error : " + error.GenerateErrorReport());
저장
using PlayFab;
using PlayFab.ClientModels;
using System;
using System.Collections.Generic;
using UnityEngine;
// 데이터 클래스 정의 (Serializable 속성 추가)
[System.Serializable]
public class DataContent
{
public string name;
public int value;
public bool isCheck;
}
public partial class PlayfabManager : MonoBehaviour
{
// 데이터 저장 완료 이벤트
public event Action<bool> OnDataSaved;
// 데이터 로드 완료 이벤트
public event Action<Dictionary<string, string>> OnDataLoaded;
// PlayFab 오류 처리
private void DisplayPlayfabError(PlayFabError error)
{
Debug.LogError("PlayFab 오류: " + error.GenerateErrorReport());
}
// JSON 데이터를 PlayFab에 저장
public void SaveJsonToPlayfab()
{
try
{
// 데이터 객체 생성
DataContent content = new DataContent
{
name = "안녕하세요",
value = 10,
isCheck = true
};
// Dictionary에 JSON 변환 데이터 추가
Dictionary<string, string> dataDic = new Dictionary<string, string>
{
{ "DataContent", JsonUtility.ToJson(content) }
};
// 데이터 저장 실행
SetUserData(dataDic);
}
catch (Exception e)
{
Debug.LogError("데이터 저장 준비 중 오류 발생: " + e.Message);
OnDataSaved?.Invoke(false);
}
}
// 여러 데이터를 한번에 저장하는 확장 버전
public void SaveMultipleJsonData(Dictionary<string, object> dataObjects)
{
try
{
Dictionary<string, string> dataDic = new Dictionary<string, string>();
// 각 객체를 JSON으로 변환하여 저장
foreach (var entry in dataObjects)
{
dataDic.Add(entry.Key, JsonUtility.ToJson(entry.Value));
}
SetUserData(dataDic);
}
catch (Exception e)
{
Debug.LogError("다중 데이터 저장 준비 중 오류 발생: " + e.Message);
OnDataSaved?.Invoke(false);
}
}
// 사용자 데이터 저장 (PlayFab API 호출)
public void SetUserData(Dictionary<string, string> data, UserDataPermission permission = UserDataPermission.Public)
{
if (data == null || data.Count == 0)
{
Debug.LogWarning("저장할 데이터가 없습니다.");
OnDataSaved?.Invoke(false);
return;
}
var request = new UpdateUserDataRequest
{
Data = data,
Permission = permission
};
try
{
Debug.Log("PlayFab에 데이터 저장 중...");
PlayFabClientAPI.UpdateUserData(request,
result => {
Debug.Log("PlayFab 데이터 저장 성공!");
OnDataSaved?.Invoke(true);
},
error => {
Debug.LogError("PlayFab 데이터 저장 실패: " + error.ErrorMessage);
DisplayPlayfabError(error);
OnDataSaved?.Invoke(false);
});
}
catch (Exception e)
{
Debug.LogError("PlayFab API 호출 중 예외 발생: " + e.Message);
OnDataSaved?.Invoke(false);
}
}
// 사용자 데이터 로드
public void GetUserData(List<string> keys = null)
{
var request = new GetUserDataRequest();
// 특정 키만 요청하는 경우
if (keys != null && keys.Count > 0)
{
request.Keys = keys;
}
PlayFabClientAPI.GetUserData(request,
result => {
Debug.Log("PlayFab 데이터 로드 성공!");
OnDataLoaded?.Invoke(result.Data);
// 사용 예시: DataContent 객체로 변환
if (result.Data.ContainsKey("DataContent"))
{
try
{
DataContent content = JsonUtility.FromJson<DataContent>(result.Data["DataContent"].Value);
Debug.Log($"로드된 데이터: 이름={content.name}, 값={content.value}, 체크={content.isCheck}");
}
catch (Exception e)
{
Debug.LogError("데이터 파싱 중 오류: " + e.Message);
}
}
},
error => {
Debug.LogError("PlayFab 데이터 로드 실패: " + error.ErrorMessage);
DisplayPlayfabError(error);
OnDataLoaded?.Invoke(null);
});
}
// 특정 사용자 데이터 삭제
public void DeleteUserData(List<string> keysToRemove)
{
if (keysToRemove == null || keysToRemove.Count == 0)
{
Debug.LogWarning("삭제할 데이터 키가 지정되지 않았습니다.");
return;
}
var request = new UpdateUserDataRequest
{
KeysToRemove = keysToRemove
};
PlayFabClientAPI.UpdateUserData(request,
result => {
Debug.Log("PlayFab 데이터 삭제 성공!");
},
DisplayPlayfabError);
}
}
불러오기
using PlayFab;
using PlayFab.ClientModels;
using System;
using System.Collections.Generic;
using UnityEngine;
// DataContent 클래스가 다른 곳에 정의되어 있다고 가정
[System.Serializable]
public class DataContent
{
public string name;
public int value;
public bool isCheck;
// ToString 오버라이드하여 디버그 출력 개선
public override string ToString()
{
return $"DataContent [name: {name}, value: {value}, isCheck: {isCheck}]";
}
}
public partial class PlayfabManager : MonoBehaviour
{
// 플레이팹 ID
public string playfabId = "";
// 데이터 로드 이벤트
public event Action<Dictionary<string, DataContent>> OnDataContentLoaded;
// 에러 핸들러
private void DisplayPlayfabError(PlayFabError error) => Debug.LogError("에러 발생: " + error.GenerateErrorReport());
// 사용자 데이터 가져오기
public void GetUserData()
{
// PlayFab ID 확인
if (string.IsNullOrEmpty(playfabId))
{
Debug.LogWarning("PlayFab ID가 설정되지 않았습니다. 현재 로그인된 사용자의 데이터를 가져옵니다.");
}
Debug.Log("사용자 데이터 로드 중...");
var request = new GetUserDataRequest()
{
PlayFabId = playfabId
};
PlayFabClientAPI.GetUserData(request,
result => {
// 데이터가 없는 경우 처리
if (result.Data == null || result.Data.Count == 0)
{
Debug.Log("저장된 데이터가 없습니다.");
OnDataContentLoaded?.Invoke(new Dictionary<string, DataContent>());
return;
}
Debug.Log($"총 {result.Data.Count}개의 데이터 항목을 로드했습니다.");
// DataContent 객체를 담을 딕셔너리
Dictionary<string, DataContent> contentDict = new Dictionary<string, DataContent>();
// 결과 처리
foreach (var eachData in result.Data)
{
try
{
// 데이터 키 확인
string key = eachData.Key;
// DataContent 형식의 데이터만 파싱
if (key.Contains("DataContent"))
{
// JSON 문자열을 DataContent 객체로 변환
DataContent content = JsonUtility.FromJson<DataContent>(eachData.Value.Value);
// 결과 저장
contentDict[key] = content;
// 디버그 출력
Debug.Log($"로드된 데이터 [{key}]: {content}");
}
else
{
Debug.Log($"다른 형식의 데이터 [{key}]: {eachData.Value.Value}");
}
}
catch (Exception ex)
{
Debug.LogError($"데이터 파싱 중 오류 발생 (키: {eachData.Key}): {ex.Message}");
}
}
// 이벤트 호출
OnDataContentLoaded?.Invoke(contentDict);
},
error => {
Debug.LogError("데이터 로드 실패: " + error.ErrorMessage);
DisplayPlayfabError(error);
OnDataContentLoaded?.Invoke(null);
});
}
// 특정 키에 해당하는 데이터만 가져오기
public void GetSpecificUserData(List<string> keys)
{
if (keys == null || keys.Count == 0)
{
Debug.LogWarning("가져올 데이터 키가 지정되지 않았습니다. 모든 데이터를 로드합니다.");
GetUserData();
return;
}
Debug.Log($"{keys.Count}개의 특정 데이터 키 로드 중...");
var request = new GetUserDataRequest()
{
PlayFabId = playfabId,
Keys = keys
};
PlayFabClientAPI.GetUserData(request,
result => {
// 데이터가 없는 경우 처리
if (result.Data == null || result.Data.Count == 0)
{
Debug.Log("요청한 키에 대한 데이터가 없습니다.");
OnDataContentLoaded?.Invoke(new Dictionary<string, DataContent>());
return;
}
Debug.Log($"요청한 키 중 {result.Data.Count}개의 데이터를 로드했습니다.");
// DataContent 객체를 담을 딕셔너리
Dictionary<string, DataContent> contentDict = new Dictionary<string, DataContent>();
// 결과 처리
foreach (var eachData in result.Data)
{
try
{
// DataContent 형식의 데이터만 파싱
if (eachData.Key.Contains("DataContent"))
{
// JSON 문자열을 DataContent 객체로 변환
DataContent content = JsonUtility.FromJson<DataContent>(eachData.Value.Value);
// 결과 저장
contentDict[eachData.Key] = content;
// 디버그 출력
Debug.Log($"로드된 데이터 [{eachData.Key}]: {content}");
}
}
catch (Exception ex)
{
Debug.LogError($"데이터 파싱 중 오류 발생 (키: {eachData.Key}): {ex.Message}");
}
}
// 이벤트 호출
OnDataContentLoaded?.Invoke(contentDict);
},
DisplayPlayfabError);
}
// 데이터 항목 하나만 가져오기 (편의 메서드)
public void GetSingleDataContent(string key)
{
GetSpecificUserData(new List<string>() { key });
}
}
참고할만한 글
유니티 플레이팹 구글 로그인 Playfab Sign In with Google Login 간단 구현
구글 로그인 SDK 설치 https://github.com/playgameservices/play-games-plugin-for-unity/tree/master/current-build GitHub - playgameservices/play-games-plugin-for-unity: Google Play Games plugin for Unity Google Play Games plugin for Unity. Contribute t
parksh3641.tistory.com
유니티 플레이팹 애플 로그인 Playfab Sign ln with Apple Login 간단 구현
애플 SDK https://github.com/lupidan/apple-signin-unity/releases/tag/v1.4.2 Release Sign in with Apple Unity Plugin v1.4.2 · lupidan/apple-signin-unity Changed Handles empty NSPersonNameComponents sent by Apple when not requesting a name, to be nil nativ
parksh3641.tistory.com