본문 바로가기
Unity/수업내용

[Unity/UGS] Cloud Save로 데이터 저장/불러오기

by 왹져박사 2024. 7. 19.

 

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>();
    }
}

 

 

데이터 저장된 모습