Advertisement
Deozaan

SaveGame.cs by Dicework Games

Jan 24th, 2012
611
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.36 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Runtime.Serialization;
  6. using System.Runtime.Serialization.Formatters.Binary;
  7. using System;
  8.  
  9. /*
  10.  * SaveGame class. Replaces Unity's PlayerPrefs for saving game data.
  11.  *
  12.  * Uses Application.persistentDataPath for cross-platform compatibility.
  13.  *
  14.  * Can be used to replace PlayerPrefs directly, eg:
  15.  * PlayerPrefs.SetInt("someInt", 1) -> SaveGame.SetInt("someInt", 1)
  16.  *  
  17.  * © Arto Koistinen / Dicework Games 2012. Free for use.
  18.  *
  19.  */
  20.  
  21. public class SaveGame  {
  22.     private static SaveGame _instance;
  23.    
  24.     private Hashtable saveData;
  25.    
  26.     private static SaveGame instance {
  27.         get {
  28.             if(_instance == null)
  29.                 new SaveGame();
  30.            
  31.             return _instance;
  32.         }
  33.     }
  34.    
  35.     private SaveGame() {
  36.         _instance = this;
  37.         saveData = new Hashtable();
  38.     }
  39.    
  40.     public static void DeleteKey(string key) {
  41.         instance.saveData.Remove(key);
  42.     }
  43.    
  44.     public static void SetString(string key, string value) {
  45.         if(instance.saveData[key] == null)
  46.             instance.saveData.Add(key, value); 
  47.         else instance.saveData[key] = value;
  48.     }
  49.    
  50.     public static void DeleteAll() {
  51.         instance.saveData = new Hashtable();
  52.     }
  53.    
  54.     public static void SetInt(string key, int value) {
  55.         if(instance.saveData[key] == null)
  56.             instance.saveData.Add(key, value); 
  57.         else instance.saveData[key] = value;
  58.     }
  59.    
  60.     /// <summary>
  61.     /// Loads the saveData hashtable from a file called "default.sav".
  62.     /// </summary>
  63.     public static void Load() {
  64.         instance.saveData = (Hashtable) LoadFromFile("default.sav");
  65.        
  66.         if(instance.saveData == null)
  67.             instance.saveData = new Hashtable();
  68.     }
  69.    
  70.     /// <summary>
  71.     /// Saves the saveData hashtable to a file called "default.sav".
  72.     /// </summary>
  73.     public static void Save() {
  74.         SaveToFile(instance.saveData, "default.sav");
  75.     }
  76.    
  77.    
  78.     // if !DEBUG is just to prevent MonoDevelop from giving errors on the default value
  79. #if !DEBUG 
  80.     public static string GetString(string key, string defaultValue = "") {
  81.         if(instance.saveData[key] == null)
  82.             return defaultValue;
  83.         else return (string) instance.saveData[key];
  84.     }
  85.    
  86.     public static int GetInt(string key, int defaultValue = 0) {
  87.         if(instance.saveData[key] == null)
  88.             return defaultValue;
  89.         else return (int) instance.saveData[key];
  90.     }
  91. #endif 
  92.    
  93.     // <summary>
  94.     // Returns the save path. This is currently identical to Application.persistentDataPath.
  95.     // </summary>
  96.     // <returns>
  97.     // A <see cref="System.String"/>
  98.     // </returns>
  99.     public static string GetPath() {
  100.         string path = Application.persistentDataPath;
  101.         // Debug.Log(path);
  102.         return path;
  103.     }
  104.    
  105.     // <summary>
  106.     // Returns true if file exists in the save directory.
  107.     // </summary>
  108.     // <param name="filename">
  109.     // A <see cref="System.String"/>
  110.     // </param>
  111.     // <returns>
  112.     // A <see cref="System.Boolean"/>
  113.     // </returns>
  114.     public static bool Exists(string filename) {
  115.         return File.Exists(GetPath() + "/" + filename);
  116.     }
  117.    
  118.     /*
  119.      *
  120.      * Utility methods for SerializableDictionary. Uncomment if needed.
  121.      *
  122.     private static SerializableDictionary<string, SerializableDictionary<string,string>> ToSerializable( SerializableDictionary<string,  SerializableDictionary<string, string>> source) {
  123.         SerializableDictionary<string, SerializableDictionary<string, string>> serializable = new SerializableDictionary<string, SerializableDictionary<string, string>>();
  124.        
  125.         foreach(string key in source.Keys) {
  126.             serializable[key] = ToSerializable(source[key]);
  127.         }
  128.        
  129.         return serializable;
  130.     }
  131.    
  132.     private static SerializableDictionary<string, LevelData> ToSerializable( SerializableDictionary<string, LevelData> source) {
  133.         SerializableDictionary<string, LevelData> serializable = new SerializableDictionary<string, LevelData>();
  134.        
  135.         foreach(string key in source.Keys) {   
  136.             serializable[key] = source[key];
  137.         }
  138.        
  139.         return serializable;
  140.     }
  141.    
  142.     private static SerializableDictionary<string, string> ToSerializable( SerializableDictionary<string, string> source) {
  143.         SerializableDictionary<string, string> serializable = new SerializableDictionary<string, string>();
  144.        
  145.         foreach(string key in source.Keys) {
  146.             serializable[key] = source[key];
  147.         }
  148.        
  149.         return serializable;
  150.     } */
  151.    
  152.    
  153.     // <summary>
  154.     // Saves a System.Object to a file. Can be used to save any (serializable) classes. Uses binary formatter to serialize the file.
  155.     // </summary>
  156.     // <param name="data">
  157.     // A <see cref="System.Object"/>
  158.     // </param>
  159.     // <param name="filename">
  160.     // A <see cref="System.String"/>
  161.     // </param>
  162.     public static void SaveToFile(System.Object data, string filename) {
  163.         string path = GetPath();
  164.         DirectoryInfo saveDirectory = new DirectoryInfo(path);
  165.        
  166.         if(!saveDirectory.Exists) {
  167.             Debug.Log("Creating save directory");
  168.             saveDirectory.Create();
  169.         }
  170.        
  171.         Debug.Log("Saving data to: " + saveDirectory.FullName + "/" + filename);
  172.         Stream stream = new FileStream(saveDirectory.FullName + "/" + filename, FileMode.Create, FileAccess.Write, FileShare.None);
  173.         BinaryFormatter formatter = new BinaryFormatter();
  174.         formatter.Serialize(stream, data);
  175.         stream.Close();
  176.     }
  177.    
  178.     // <summary>
  179.     // Loads a System.Object from a file. Uses binary formatter to deserialize.
  180.     // </summary>
  181.     // <param name="filename">
  182.     // A <see cref="System.String"/>
  183.     // </param>
  184.     // <returns>
  185.     // A <see cref="System.Object"/>
  186.     // </returns>
  187.    
  188.     public static System.Object LoadFromFile(string filename) {
  189.         Debug.Log("Load From file " + filename);
  190.         BinaryFormatter formatter = new BinaryFormatter();
  191.         string path = GetPath();
  192.         DirectoryInfo saveDirectory = new DirectoryInfo(path);
  193.        
  194.         if(!saveDirectory.Exists) {    
  195.             return null;
  196.         }
  197.        
  198.         //FileInfo saveFile = saveDirectory.GetFile(filename);
  199.        
  200.         FileInfo[] files = saveDirectory.GetFiles("*.sav");
  201.         string saveFile = null;
  202.        
  203.         foreach(FileInfo file in files) {
  204.             if(file.Name == filename) {
  205.                 saveFile = file.FullName;
  206.                 break;
  207.             }
  208.         }
  209.        
  210.         if(saveFile == null) {
  211.             Debug.LogWarning("Save file not found.");
  212.             return null;
  213.         }
  214.        
  215.         Stream stream = new FileStream(saveFile, FileMode.Open, FileAccess.Read, FileShare.None);
  216.        
  217.         if(stream == null) {
  218.             return null;
  219.         }
  220.        
  221.         if(stream.Length > 0) {
  222.             System.Object data = formatter.Deserialize(stream);
  223.             Debug.Log("Load successful!");
  224.             return data;
  225.         } else {
  226.             Debug.LogWarning("Stream.Length = 0!");
  227.             return null;
  228.         }
  229.     }
  230. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement