daily pastebin goal
7%
SHARE
TWEET

Untitled

a guest Dec 7th, 2017 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization.Formatters.Binary;
  4. using UnityEngine;
  5.  
  6. namespace MyProject
  7. {
  8.     public class StorageHandler : MonoBehaviour
  9.     {
  10.         // <summary>
  11.         // Serialize an object to the devices File System.
  12.         // </summary>
  13.         // <param name="objectToSave">The Object that will be Serialized.</param>
  14.         // <param name="fileName">Name of the file to be Serialized.</param>
  15.         public void SaveData(object objectToSave, string fileName)
  16.         {
  17.             // Add the File Path together with the files name and extension.
  18.             // We will use .bin to represent that this is a Binary file.
  19.             string FullFilePath = Application.persistentDataPath + "/" + fileName + ".bin";
  20.             // We must create a new Formattwr to Serialize with.
  21.             BinaryFormatter Formatter = new BinaryFormatter();
  22.             // Create a streaming path to our new file location.
  23.             FileStream fileStream = new FileStream(FullFilePath, FileMode.Create);
  24.             // Serialize the objedt to the File Stream
  25.             Formatter.Serialize(fileStream, objectToSave);
  26.             // FInally Close the FileStream and let the rest wrap itself up.
  27.             fileStream.Close();
  28.         }
  29.         // <summary>
  30.         // Deserialize an object from the FileSystem.
  31.         // </summary>
  32.         // <param name="fileName">Name of the file to deserialize.</param>
  33.         // <returns>Deserialized Object</returns>
  34.         public object LoadData(string fileName)
  35.         {
  36.             string FullFilePath = Application.persistentDataPath + "/" + fileName + ".bin";
  37.             // Check if our file exists, if it does not, just return a null object.
  38.             if (File.Exists(FullFilePath))
  39.             {
  40.                 BinaryFormatter Formatter = new BinaryFormatter();
  41.                 FileStream fileStream = new FileStream(FullFilePath, FileMode.Open);
  42.                 object obj = Formatter.Deserialize(fileStream);
  43.                 fileStream.Close();
  44.                 // Return the uncast untyped object.
  45.                 return obj;
  46.             }
  47.             else
  48.             {
  49.                 return null;
  50.             }
  51.         }
  52.     }
  53. }
RAW Paste Data
Top