Advertisement
noradninja

Sample serializer/deserializer

Sep 4th, 2022
1,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.74 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. using System.IO;
  6. using UnityEngine;
  7. using UnityEngine.UI;
  8.  
  9.  
  10.  
  11. /*This script serializes a binary file for saving data. For Vita use, dataPath should be formatted as ux0:/data/someDirectoryName/ in the Inspector.
  12. You should also define savePrefix in some fashion, otherwise youre saves will just be based on the number of the slot you've selected*/
  13. public class SaveSerial : MonoBehaviour {
  14.    
  15.     public GameObject saveManager;
  16.     public string dataPath;
  17.     public string savePrefix;
  18.     public string saveFileName;
  19.     public bool hasLoaded;
  20.     public int slotSelector;
  21. // Set up the data we are saving to the file
  22.     public string levelToSave;
  23.     public GameObject player;
  24.     public List<GameObject> medList;
  25.     public List <GameObject> battList;
  26.     public List<GameObject> lwList;
  27.     public List<GameObject> hwList;
  28.  
  29.    
  30.  
  31. void Start() {
  32.     SetScenes.sceneToLoad = "LoadScreen";
  33.     levelToSave = this.GetComponent<SceneLoadTrigger>().currentScene;
  34. //ignore this if we are in the editor
  35.  
  36. //create directory on the Vita for our save files if it doesn't exist
  37.     if(!Directory.Exists(dataPath)){
  38.         Directory.CreateDirectory(dataPath);
  39.     }
  40. }
  41.  
  42.  void Update()
  43.  {
  44.      slotSelector = SetScenes.currentScene == "Title" ? saveManager.GetComponent<LoadManager_Inputs>().selectedSlot : saveManager.GetComponent<SaveManager_Inputs>().selectedSlot;
  45.      //set save file name based on the slot selected so we know which file we are loading/saving
  46.     saveFileName = (savePrefix + slotSelector + ".sav");
  47.  }
  48.    
  49. //this is the class we are using to store our data we want to save
  50. [System.Serializable]
  51.  
  52. public class SaveData
  53.     {
  54.         public string savedLevel;
  55.         public float[] playerPosition = new float [3];
  56.         public float[] playerRotation = new float [3];
  57.         public int playerMedkits;
  58.         public int playerStimulants;
  59.         public int playerBatteries;
  60.         public float playerHealth;
  61.         public List<int> collectedMeds = new List<int>();
  62.         public List<int> collectedBattery = new List<int>();
  63.         public List<int> collectedLightWep = new List<int>();
  64.         public List<int> collectedHvyWep = new List<int>();
  65.  
  66.     }
  67. //create a binary file, copy our data from the game to a SaveData instance
  68. public void Save()
  69.     {
  70.         //data prep
  71.         medList.Clear();
  72.         medList.AddRange(GameObject.FindGameObjectsWithTag("Meds"));
  73.         battList.Clear();
  74.         battList.AddRange(GameObject.FindGameObjectsWithTag("Battery"));
  75.         hwList.Clear();
  76.         hwList.AddRange(GameObject.FindGameObjectsWithTag("Heavy"));
  77.         lwList.Clear();
  78.         lwList.AddRange(GameObject.FindGameObjectsWithTag("Light"));
  79.  
  80.         var bf = new BinaryFormatter();
  81.         var file = File.Create(dataPath + saveFileName);
  82.         var position = player.transform.position;
  83.         var rotation = player.transform.rotation;
  84.         var data = new SaveData();
  85.         //data needed for reloading on game load
  86.         data.savedLevel = levelToSave;
  87.         data.playerPosition[0] = position.x;
  88.         data.playerPosition[1] = position.y;
  89.         data.playerPosition[2] = position.z;
  90.         data.playerRotation[0] = rotation.eulerAngles.x;
  91.         data.playerRotation[1] = rotation.eulerAngles.y;
  92.         data.playerRotation[2] = rotation.eulerAngles.z;
  93.         data.playerBatteries = InventoryManager.batteryCount;
  94.         data.playerMedkits = InventoryManager.medCount;
  95.         data.playerStimulants = InventoryManager.stimCount;
  96.         data.playerHealth = player.GetComponent<PlayerController>().health;
  97.  
  98.         // //spin through list data to store identifiers
  99.        
  100.         //meds
  101.         for (var i = 0; i < medList.Count; i++){
  102.             data.collectedMeds.Add(medList[i].gameObject.GetComponent<Item_Enumerator>().identifier);
  103.         }
  104.         //batteries
  105.         for (var i = 0; i < battList.Count; i++){
  106.             data.collectedBattery.Add(battList[i].gameObject.GetComponent<Item_Enumerator>().identifier);
  107.         }
  108.         //light weapons
  109.         for (var i = 0; i < lwList.Count; i++){
  110.             data.collectedLightWep.Add(lwList[i].gameObject.GetComponent<Item_Enumerator>().identifier);
  111.         }
  112.         //heavy weapons
  113.         for (var i = 0; i < hwList.Count; i++){
  114.             data.collectedHvyWep.Add(hwList[i].gameObject.GetComponent<Item_Enumerator>().identifier);
  115.         }
  116.        
  117.         bf.Serialize(file, data);
  118.         PlayerPrefs.SetInt("haveSavedGame", 1);
  119.         PlayerPrefs.Save();
  120.         Debug.Log(data.savedLevel + " saved!");
  121.         file.Close();  
  122.     }
  123. //checks if the file exists, if so load the data from it and copy it back to our game
  124. public void Load()
  125.     {
  126.         if (File.Exists(dataPath + saveFileName))
  127.         {
  128.             var bf = new BinaryFormatter();
  129.             var file =  File.Open(dataPath + saveFileName, FileMode.Open);
  130.             var data = (SaveData)bf.Deserialize(file);
  131.             file.Close();
  132.             levelToSave = data.savedLevel;
  133.  
  134.             Debug.Log (levelToSave);
  135.             hasLoaded = true;
  136.             SetScenes.nextScene = levelToSave;
  137.             SetScenes.playerPosition = new Vector3( data.playerPosition[0],
  138.                                                     data.playerPosition[1],
  139.                                                     data.playerPosition[2] );
  140.             SetScenes.playerRotation = Quaternion.Euler( data.playerRotation[0],
  141.                                                          data.playerRotation[1],
  142.                                                          data.playerRotation[2] );
  143.             SetScenes.playerBatteries = data.playerBatteries;
  144.             SetScenes.playerHealth = data.playerHealth;
  145.             SetScenes.playerMedkits = data.playerMedkits;
  146.             SetScenes.playerStimulants = data.playerStimulants;
  147.             SetScenes.MedsRemaining = data.collectedMeds;
  148.             SetScenes.BatteryRemaining = data.collectedBattery;
  149.             SetScenes.LightWepRemaining = data.collectedLightWep;
  150.             SetScenes.HvyWepRemaining = data.collectedHvyWep;
  151.             PlayerPrefs.SetInt("hasLoadedFile",1);
  152.             PlayerPrefs.Save();
  153.         }
  154.         else Debug.Log("No Save File Exists to Load!");
  155.     }
  156. //checks if the file exists, if it does, delete the file and reset our game variables
  157. public void Reset()
  158.     {
  159.  
  160.         if (File.Exists(dataPath + saveFileName))
  161.         {
  162.             File.Delete(dataPath + saveFileName);
  163.             levelToSave = "";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement