Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Unity.Services.CloudSave;
- using UnityEngine;
- using static Newtonsoft.Json.JsonConvert;
- namespace JS
- {
- public class CloudSave : ISaveClient
- {
- public async Task Save(string key, object value) =>
- await Call( CloudSaveService.Instance.Data.Player.SaveAsync(
- new Dictionary<string, object> { { key, value } }));
- public async Task Save(params (string key, object value)[] values) =>
- await Call( CloudSaveService.Instance.Data.Player.SaveAsync(
- values.ToDictionary(item => item.key, item => item.value)));
- public async Task<T> Load<T>(string key)
- {
- var query = await Call( CloudSaveService.Instance.Data.Player.LoadAsync(new HashSet<string> { key }));
- return query.TryGetValue(key, out var value) ? Deserialize<T>(value.Value.GetAsString()) : default;
- }
- public async Task<IEnumerable<T>> Load<T>(params string[] keys)
- {
- var query = await Call( CloudSaveService.Instance.Data.Player.LoadAsync(keys.ToHashSet()));
- return keys.Select(k =>
- {
- if (query.TryGetValue(k, out var value))
- return value != null ? Deserialize<T>(value.Value.GetAsString()) : default;
- return default;
- });
- }
- public async Task Delete(string key) => await Call( CloudSaveService.Instance.Data.Player.DeleteAsync(key));
- public async Task DeleteAll()
- {
- var keys = await Call( CloudSaveService.Instance.Data.Player.ListAllKeysAsync());
- var tasks = keys.Select(k => CloudSaveService.Instance.Data.Player.DeleteAsync(k.Key)).ToList();
- await Call(Task.WhenAll(tasks));
- }
- static T Deserialize<T>(string input)
- {
- if (typeof(T) == typeof(string)) return (T)(object)input;
- return DeserializeObject<T>(input);
- }
- static async Task Call(Task action)
- {
- try
- {
- await action;
- }
- catch (CloudSaveValidationException e)
- {
- Debug.LogError(e);
- }
- catch (CloudSaveRateLimitedException e)
- {
- Debug.LogError(e);
- }
- catch (CloudSaveException e)
- {
- Debug.LogError(e);
- }
- }
- static async Task<T> Call<T>(Task<T> action)
- {
- try
- {
- return await action;
- }
- catch (CloudSaveValidationException e)
- {
- Debug.LogError(e);
- }
- catch (CloudSaveRateLimitedException e)
- {
- Debug.LogError(e);
- }
- catch (CloudSaveException e)
- {
- Debug.LogError(e);
- }
- return default;
- }
- }
- public interface ISaveClient
- {
- Task Save(string key, object value);
- Task Save(params (string key, object value)[] values);
- Task<T> Load<T>(string key);
- Task<IEnumerable<T>> Load<T>(params string[] keys);
- Task Delete(string key);
- Task DeleteAll();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement