Advertisement
Guest User

Save and Load

a guest
May 27th, 2019
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.64 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Xml.Serialization;
  4. using System.IO;
  5. using UnityEngine;
  6.  
  7. public class SaveAndLoad : MonoBehaviour
  8. {
  9.  
  10.     public VariableManager varMan; //Script which stores the variables you wish to save.
  11.     static string coinFilePath = ReturnPath(); //Path to the loacllay stored save data.
  12.  
  13.     //Called when the object is created.
  14.     void Awake()
  15.     {
  16.         //Make object transferable through scenes.
  17.         DontDestroyOnLoad(this.gameObject);
  18.        
  19.         //If there is locally saved data, load it.
  20.         if (CheckForExistingFile () == true)
  21.         {
  22.             LoadCurrency ();
  23.         }
  24.     }
  25.    
  26.     //Returns the path to the locally saved data
  27.     static string ReturnPath()
  28.     {
  29.         string coinFilePath = Path.Combine(Application.persistentDataPath, "coins.xml");
  30.         return coinFilePath;
  31.     }
  32.  
  33.     //Checks if loadable data is present.
  34.     bool CheckForExistingFile()
  35.     {        
  36.         if (!File.Exists (coinFilePath))
  37.         {
  38.             return false;
  39.         }
  40.         else
  41.         {
  42.             return true;
  43.         }
  44.  
  45.     }
  46.  
  47.     // Loads the current currency amounts
  48.     void LoadCurrency ()
  49.     {
  50.        
  51.         var serializer = new XmlSerializer(typeof(int));
  52.         var stream = new FileStream(coinFilePath, FileMode.Open);
  53.         int container = (int)serializer.Deserialize(stream);
  54.         stream.Close();
  55.  
  56.         varMan.coins = container;
  57.  
  58.         Debug.Log("coins: " + varMan.coins);
  59.     }
  60.    
  61.     // Saves the current currency amounts
  62.     public void SaveCurrency()
  63.     {
  64.         var serializer = new XmlSerializer(typeof(int));
  65.         var stream = new FileStream(coinFilePath, FileMode.Create);
  66.         serializer.Serialize(stream, varMan.coins);
  67.         stream.Close();
  68.  
  69.         string text = stream.ToString ();
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement