Last active
February 8, 2022 21:35
-
-
Save Anthelmed/8600100da0d5e28528dcf4977ed582d2 to your computer and use it in GitHub Desktop.
Unity Read/Write SaveAsync/LoadAsync streamingAssets file utils
This file contains 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.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