Advertisement
dronkowitz

SaveLoad.cs

Dec 28th, 2022 (edited)
1,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System.Runtime.Serialization.Formatters.Binary;
  2. using System.IO;
  3. using UnityEngine;
  4.  
  5.  
  6. public static class SaveLoad
  7. {
  8.  
  9.     private static string SaveLocation(int saveID)
  10.     {
  11.         return $"{Application.persistentDataPath}/save{saveID}.sav";
  12.     }
  13.     public static SaveData currentSave;
  14.  
  15.     public static void SaveCurrentData(int saveId)
  16.     {
  17.         Inventory playerInventory = GameObject.FindGameObjectWithTag("Player").GetComponent<Inventory>();
  18.         currentSave.inventoryData = DataConversion.ItemsToString(playerInventory.backPack);
  19.         string destination = SaveLocation(saveId);
  20.         FileStream file;
  21.         if (File.Exists(destination))
  22.         {
  23.             file = File.OpenWrite(destination);
  24.         }
  25.         else
  26.         {
  27.             file = File.Create(destination);
  28.         }
  29.  
  30.         BinaryFormatter bf = new BinaryFormatter();
  31.         bf.Serialize(file, currentSave);
  32.         file.Close();
  33.     }
  34.  
  35.     public static bool LoadFile(int saveId)
  36.     {
  37.         string destination = SaveLocation(saveId); ;
  38.         FileStream file;
  39.         if (File.Exists(destination))
  40.         {
  41.             file = File.OpenRead(destination);
  42.         }
  43.         else
  44.         {
  45.             Debug.LogWarning("File does not exist");
  46.             return false;
  47.         }
  48.  
  49.         BinaryFormatter bf = new BinaryFormatter();
  50.         currentSave = (SaveData)bf.Deserialize(file);
  51.         file.Close();
  52.         return true;
  53.     }
  54.  
  55. }
  56. [System.Serializable]
  57. public struct SaveData
  58. {
  59.     public string equipment;
  60.     public string inventoryData;
  61.     public string saveName;
  62.     public string questData;
  63.     public int money;
  64.     public int saveDate;
  65.     public float[] playerPosition;
  66.     public float[] playerRotation;
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement