using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Unity.Services.Authentication;
using Unity.Services.CloudSave;
using Unity.Services.Core;
using UnityEngine;
using UnityEngine.UI;
[Serializable]
public struct PlayerData
{
public string name;
public int level;
public int xp;
public List<ItemData> itemDatas;
}
[Serializable]
public struct ItemData
{
public string name;
public int value;
public string icon;
}
public class CloudSaveManager : MonoBehaviour
{
[SerializeField] private Button btnSingleDataSave, btnMultiDataSave, btnMuliDataLoad;
[SerializeField] private PlayerData playerData;
private async void Awake()
{
await UnityServices.InitializeAsync();
AuthenticationService.Instance.SignedIn += () =>
{
string playerId = AuthenticationService.Instance.PlayerId;
Debug.Log("player id : " + playerId);
};
await this.SignInAsync();
this.btnSingleDataSave.onClick.AddListener(async () =>
{
await this.SaveSingleDataAsync();
});
this.btnMultiDataSave.onClick.AddListener(async () =>
{
await this.SaveMultiDataAsync<PlayerData>("PlayerMultiData", playerData);
});
this.btnMuliDataLoad.onClick.AddListener(async () =>
{
await this.LoadDataAsync<PlayerData>("PlayerMultiData");
});
}
private async Task SignInAsync()
{
await AuthenticationService.Instance.SignInAnonymouslyAsync();
}
public async Task SaveSingleDataAsync()
{
//저장할 데이터
var data = new Dictionary<string, object>
{
{"player_name", "Nam HyeRim" },
{"level", 9999 },
{"xp", 99999 }
};
//저장 메소드
await CloudSaveService.Instance.Data.Player.SaveAsync(data);
Debug.Log("saved data");
}
private async Task SaveMultiDataAsync<T>(string key, T saveData)
{
var data = new Dictionary<string, object>
{
{ key, saveData }
};
await CloudSaveService.Instance.Data.Player.SaveAsync(data);
Debug.Log("saved multi data");
}
//복수 데이터 로드
public async Task LoadDataAsync<T>(string key)
{
var loadData = await CloudSaveService.Instance.Data.Player.LoadAsync(new HashSet<string> { key});
loadData.TryGetValue(key, out var data);
//Json 타입으로 변환없이 바로 추출하는 방식
this.playerData = data.Value.GetAs<PlayerData>();
}
}
데이터 저장된 모습
'Unity > 수업내용' 카테고리의 다른 글
[Unity/최적화] 최적화 할 것 메모 (1) | 2024.07.19 |
---|---|
[Unity/UGS] Remote Config 활용하기 (0) | 2024.07.19 |
[Unity/프로파일링] 프로파일러들 (0) | 2024.07.19 |
[RestAPI]공공데이터 OpenAPI 데이터 활용하기 (0) | 2024.07.19 |
[Unity 3D] IK 역운동학 (0) | 2023.05.22 |