Advertisement
GeeItSomeLaldy

Basic Unity File System Service for save/loading of Objects

Nov 11th, 2015
309
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System.Text;
  8. using UnityEngine;
  9.  
  10. namespace Services
  11. {
  12.     public static class FileSystemService
  13.     {
  14.         private static void Setup()
  15.         {
  16. #if UNITY_IOS
  17.             //Need to use Reflection Serializer on IOS (slower, but IOS doesn't allow code generation)
  18.             if (Environment.GetEnvironmentVariable("MONO_REFLECTION_SERIALIZER") != "yes")
  19.             {
  20.                 Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
  21.             }
  22. #endif
  23.         }
  24.         private static string GetSavePath(string filename)
  25.         {
  26.             var path = string.Format("{0}/userdata/{1}", Application.persistentDataPath, filename);
  27.             FileInfo file = new FileInfo(path);
  28.             if(!file.Directory.Exists) file.Directory.Create();
  29.             return path;
  30.         }
  31.         public static void SaveDataToFile(string filename, object data)
  32.         {
  33.             Setup();
  34.             string filePath = GetSavePath(filename);
  35.             using (FileStream fs = File.OpenWrite(filePath))
  36.             {
  37.                 BinaryFormatter formatter = new BinaryFormatter();
  38.                 formatter.Serialize(fs, data);
  39.             }
  40.         }
  41.        
  42.  
  43.         public static T LoadDataFromFile<T>(string filename)
  44.         {
  45.             string filePath = GetSavePath(filename);
  46.             if (!File.Exists(filePath)) return default(T);
  47.             Setup();
  48.             try {
  49.                 using (FileStream fs = File.OpenRead(filePath))
  50.                 {
  51.                     BinaryFormatter formatter = new BinaryFormatter();
  52.                     object data = formatter.Deserialize(fs);
  53.                     return (T)data;
  54.                 }
  55.             } catch(Exception ex)
  56.             {
  57.                 Debug.LogError(ex.Message);
  58.                 return default(T);
  59.             }
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement