Created
February 17, 2024 06:19
-
-
Save Matthew-J-Spencer/ccb85a946956a81c41e6abcad804069f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Unity.Services.CloudSave; | |
using Unity.Services.CloudSave.Internal; | |
using UnityEngine; | |
public class UnityCloudSave : ICloudSave | |
{ | |
private readonly Lazy<IDataService> _client = new(() => CloudSaveService.Instance.Data); | |
public async Task Save(string key, object value) | |
{ | |
var data = new Dictionary<string, object> { { key, value } }; | |
await _client.Value.Player.SaveAsync(data); | |
} | |
public async Task Save(params (string key, object value)[] values) | |
{ | |
var data = values.ToDictionary(item => item.key, item => item.value); | |
await _client.Value.Player.SaveAsync(data); | |
} | |
public async Task<T> Load<T>(string key) | |
{ | |
var query = await _client.Value.Player.LoadAsync(new HashSet<string> { key }); | |
return query.TryGetValue(key, out var value) ? value.Value.GetAs<T>() : default; | |
} | |
public async Task<List<T>> LoadAllCustom<T>(string key) | |
{ | |
var query = await _client.Value.Custom.LoadAllAsync(key); | |
return query.Values.Select(v => v.Value.GetAs<T>()).ToList(); | |
} | |
public async Task<IEnumerable<T>> Load<T>(params string[] keys) | |
{ | |
var query = await _client.Value.Player.LoadAsync(keys.ToHashSet()); | |
return keys.Select(k => | |
{ | |
if (query.TryGetValue(k, out var value)) | |
{ | |
return value != null ? value.Value.GetAs<T>() : default; | |
} | |
return default; | |
}); | |
} | |
public async Task Delete(string key) | |
{ | |
await _client.Value.Player.DeleteAsync(key); | |
} | |
public async Task DeleteAll() | |
{ | |
var keys = await _client.Value.Player.ListAllKeysAsync(); | |
var tasks = keys.Select(k => _client.Value.Player.DeleteAsync(k.Key)).ToList(); | |
await Task.WhenAll(tasks); | |
} | |
private static async Task Call(Task action) | |
{ | |
try | |
{ | |
await action; | |
} | |
catch (CloudSaveValidationException) | |
{ | |
throw; | |
} | |
catch (CloudSaveRateLimitedException) | |
{ | |
throw; | |
} | |
catch (CloudSaveException) | |
{ | |
throw; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment