Skip to content

Instantly share code, notes, and snippets.

@Anthelmed
Last active February 8, 2022 21:35
Show Gist options
  • Save Anthelmed/8600100da0d5e28528dcf4977ed582d2 to your computer and use it in GitHub Desktop.
Save Anthelmed/8600100da0d5e28528dcf4977ed582d2 to your computer and use it in GitHub Desktop.
Unity Read/Write SaveAsync/LoadAsync streamingAssets file utils
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json; // https://docs.unity3d.com/Packages/[email protected]/manual/index.html
using UnityEngine;
public static class FileUtils
{
public static string RootDirectory
{
get
{
#if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
return Application.streamingAssetsPath;
#elif UNITY_IOS
return Application.dataPath + "/Raw";
#elif UNITY_ANDROID
return "jar:file://" + Application.dataPath + "!/assets";
#endif
}
}
public static string ReadFile(string fileName)
{
string assetsDirectory = RootDirectory;
var filePath = Path.Combine(assetsDirectory, fileName);
var data = "";
if (File.Exists(filePath))
data = File.ReadAllText(filePath);
else
Debug.LogError($"File {fileName} at {assetsDirectory} doesn't exist");
return data;
}
public static void WriteFile(string data, string fileName)
{
string assetsDirectory = RootDirectory;
var filePath = Path.Combine(assetsDirectory, fileName);
if (File.Exists(filePath))
{
File.WriteAllText(filePath, data);
}
else
Debug.LogError($"File {fileName} at {assetsDirectory} doesn't exist");
}
public static async void SaveFileAsync<T>(T value, string fileName, CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource?.Cancel();
cancellationTokenSource = new CancellationTokenSource();
var data = await Task.Run(() => JsonConvert.SerializeObject(value), cancellationTokenSource.Token);
WriteFile(data, fileName);
}
public static async Task<T> LoadFileAsync<T>(string fileName, CancellationTokenSource cancellationTokenSource)
{
cancellationTokenSource?.Cancel();
cancellationTokenSource = new CancellationTokenSource();
var data = ReadFile(fileName);
return await Task.Run(() => JsonConvert.DeserializeObject<T>(data), cancellationTokenSource.Token);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment