Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Text;
- using UnityEngine;
- namespace Services
- {
- public static class FileSystemService
- {
- private static void Setup()
- {
- #if UNITY_IOS
- //Need to use Reflection Serializer on IOS (slower, but IOS doesn't allow code generation)
- if (Environment.GetEnvironmentVariable("MONO_REFLECTION_SERIALIZER") != "yes")
- {
- Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
- }
- #endif
- }
- private static string GetSavePath(string filename)
- {
- var path = string.Format("{0}/userdata/{1}", Application.persistentDataPath, filename);
- FileInfo file = new FileInfo(path);
- if(!file.Directory.Exists) file.Directory.Create();
- return path;
- }
- public static void SaveDataToFile(string filename, object data)
- {
- Setup();
- string filePath = GetSavePath(filename);
- using (FileStream fs = File.OpenWrite(filePath))
- {
- BinaryFormatter formatter = new BinaryFormatter();
- formatter.Serialize(fs, data);
- }
- }
- public static T LoadDataFromFile<T>(string filename)
- {
- string filePath = GetSavePath(filename);
- if (!File.Exists(filePath)) return default(T);
- Setup();
- try {
- using (FileStream fs = File.OpenRead(filePath))
- {
- BinaryFormatter formatter = new BinaryFormatter();
- object data = formatter.Deserialize(fs);
- return (T)data;
- }
- } catch(Exception ex)
- {
- Debug.LogError(ex.Message);
- return default(T);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement