evelynshilosky

SaveManager - Part 34

Mar 8th, 2024 (edited)
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.08 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using UnityEngine;
  7. using UnityEngine.SceneManagement;
  8.  
  9. public class SaveManager : MonoBehaviour
  10. {
  11.     public static SaveManager Instance { get; set; }
  12.     private void Awake()
  13.     {
  14.         if (Instance != null && Instance != this)
  15.         {
  16.             Destroy(gameObject);
  17.         }
  18.         else
  19.         {
  20.             Instance = this;
  21.         }
  22.  
  23.         DontDestroyOnLoad(gameObject);
  24.  
  25.     }
  26.  
  27.     // Json Project Save Path
  28.     string jsonPathProject;
  29.     // Json External/Real Save Path
  30.     string jsonPathPersistant;
  31.     // Binary Save Path
  32.     string binaryPath;
  33.  
  34.  
  35.     string fileName = "SaveGame";
  36.  
  37.     public bool isSavingToJson;
  38.  
  39.     public bool isLoading;
  40.  
  41.     public Canvas loadingScreen;
  42.  
  43.  
  44.     private void Start()
  45.     {
  46.         jsonPathProject = Application.dataPath + Path.AltDirectorySeparatorChar;
  47.         jsonPathPersistant = Application.persistentDataPath + Path.AltDirectorySeparatorChar;
  48.         binaryPath = Application.persistentDataPath + Path.AltDirectorySeparatorChar;
  49.     }
  50.  
  51.     #region || ---------- General Section ---------- ||
  52.  
  53.     #region || ---------- Saving ---------- ||
  54.    
  55.     public void SaveGame(int slotNumber)
  56.     {
  57.         AllGameData data = new AllGameData();
  58.  
  59.         data.playerData = GetPlayerData();
  60.  
  61.         data.environmentData = GetEnvironmentData();
  62.  
  63.         SavingTypeSwitch(data, slotNumber);
  64.     }
  65.  
  66.     private EnvironmentData GetEnvironmentData()
  67.     {
  68.         List<string> itemsPickedup = InventorySystem.Instance.itemsPickedup;
  69.  
  70.         // Get all Trees and Stumps
  71.         List<TreeData> treesToSave = new List<TreeData>();
  72.  
  73.         foreach (Transform tree in EnvironmentManager.Instance.allTrees.transform)
  74.         {
  75.             if (tree.CompareTag("Tree"))
  76.             {
  77.                 var td = new TreeData();
  78.                 td.name = "Tree_Parent (1)"; // This needs to be the same as prefab name
  79.                 td.position = tree.position;
  80.                 td.rotation = new Vector3(tree.rotation.x, tree.rotation.y, tree.rotation.z);
  81.  
  82.                 treesToSave.Add(td);
  83.             }
  84.             else
  85.             {
  86.                 var td = new TreeData();
  87.                 td.name = "Stump"; // This needs to be the same as prefab name
  88.                 td.position = tree.position;
  89.                 td.rotation = new Vector3(tree.rotation.x, tree.rotation.y, tree.rotation.z);
  90.  
  91.                 treesToSave.Add(td);
  92.             }
  93.         }
  94.  
  95.         // Get all animals
  96.         List<string> allAnimals = new List<string>();
  97.         foreach (Transform animalType in EnvironmentManager.Instance.allAnimals.transform)
  98.         {
  99.             foreach (Transform animal in animalType.transform)
  100.             {
  101.                 allAnimals.Add(animal.gameObject.name);
  102.             }
  103.         }
  104.  
  105.         // Get information about storage boxes in the scene
  106.         List<StorageData> allStorage = new List<StorageData>();
  107.         foreach (Transform placeable in EnvironmentManager.Instance.placeables.transform)
  108.         {
  109.             if (placeable.gameObject.GetComponent<StorageBox>())
  110.             {
  111.                 var sd = new StorageData();
  112.                 sd.items = placeable.gameObject.GetComponent<StorageBox>().items;
  113.                 sd.position = placeable.position;
  114.                 sd.rotation = new Vector3(placeable.rotation.x, placeable.rotation.y, placeable.rotation.z);
  115.  
  116.                 allStorage.Add(sd);
  117.             }
  118.         }
  119.  
  120.         return new EnvironmentData(itemsPickedup, treesToSave, allAnimals, allStorage);
  121.     }
  122.  
  123.  
  124.     private PlayerData GetPlayerData()
  125.     {
  126.         float[] playerStats = new float[3];
  127.         playerStats[0] = PlayerState.Instance.currentHealth;
  128.         playerStats[1] = PlayerState.Instance.currentCalories ;
  129.         playerStats[2] = PlayerState.Instance.currentHydrationPercent;
  130.  
  131.         float[] playerPosAndRot = new float[6];
  132.         playerPosAndRot[0] = PlayerState.Instance.playerBody.transform.position.x;
  133.         playerPosAndRot[1] = PlayerState.Instance.playerBody.transform.position.y;
  134.         playerPosAndRot[2] = PlayerState.Instance.playerBody.transform.position.z;
  135.  
  136.         playerPosAndRot[3] = PlayerState.Instance.playerBody.transform.rotation.x;
  137.         playerPosAndRot[4] = PlayerState.Instance.playerBody.transform.rotation.y;
  138.         playerPosAndRot[5] = PlayerState.Instance.playerBody.transform.rotation.z;
  139.  
  140.         string[] inventory = InventorySystem.Instance.itemList.ToArray();
  141.  
  142.         string[] quickSlots = GetQuickSlotsContent();
  143.  
  144.         return new PlayerData(playerStats, playerPosAndRot, inventory, quickSlots);
  145.  
  146.     }
  147.  
  148.     private string[] GetQuickSlotsContent()
  149.     {
  150.         List<string> temp = new List<string>();
  151.  
  152.         foreach (GameObject slot in EquipSystem.Instance.quickSlotsList)
  153.         {
  154.             if (slot.transform.childCount != 0)
  155.             {
  156.                 string name = slot.transform.GetChild(0).name;
  157.                 string str2 = "(Clone)";
  158.                 string cleanName = name.Replace(str2, "");
  159.                 temp.Add(cleanName);
  160.             }
  161.         }
  162.  
  163.         return temp.ToArray();
  164.     }
  165.  
  166.     public void SavingTypeSwitch(AllGameData gameData, int slotNumber)
  167.     {
  168.         if (isSavingToJson)
  169.         {
  170.             SaveGameDataToJsonFile(gameData, slotNumber);
  171.         }
  172.         else
  173.         {
  174.             SaveGameDataToBinaryFile(gameData, slotNumber);
  175.         }
  176.     }
  177.     #endregion
  178.  
  179.     #region || ---------- Loading ---------- ||
  180.  
  181.     public AllGameData LoadingTypeSwitch(int slotNumber)
  182.     {
  183.         if (isSavingToJson)
  184.         {
  185.             AllGameData gameData = LoadGameDataFromJsonFile(slotNumber);
  186.             return gameData;
  187.         }
  188.         else
  189.         {
  190.             AllGameData gameData = LoadGameDataFromBinaryFile(slotNumber);
  191.             return gameData;
  192.         }
  193.     }
  194.  
  195.     public void LoadGame(int slotNumber)
  196.     {
  197.         // Player Data
  198.         SetPlayerData(LoadingTypeSwitch(slotNumber).playerData);
  199.  
  200.         // Environment Data
  201.         SetEnvironmentData(LoadingTypeSwitch(slotNumber).environmentData);
  202.  
  203.          isLoading = false;
  204.  
  205.         DisableLoadingScreen();
  206.     }
  207.  
  208.     private void SetEnvironmentData(EnvironmentData environmentData)
  209.     {
  210.         // Picked Up Items \\
  211.  
  212.         foreach (Transform itemType in EnvironmentManager.Instance.allItems.transform)
  213.         {
  214.             foreach (Transform item in itemType.transform)
  215.             {
  216.                 if (environmentData.pickedupItems.Contains(item.name))
  217.                 {
  218.                     Destroy(item.gameObject);
  219.                 }
  220.  
  221.             }
  222.         }
  223.  
  224.         // So the itemsPickedup will be persistant.
  225.         InventorySystem.Instance.itemsPickedup = environmentData.pickedupItems;
  226.  
  227.         // TREES \\
  228.  
  229.         // Remove all default trees
  230.         foreach (Transform tree in EnvironmentManager.Instance.allTrees.transform)
  231.         {
  232.             Destroy(tree.gameObject);
  233.         }
  234.  
  235.         // Add trees and stumps
  236.         foreach (TreeData tree in environmentData.treeData)
  237.         {
  238.             var treePrefab = Instantiate(Resources.Load<GameObject>(tree.name),
  239.                 new Vector3(tree.position.x, tree.position.y, tree.position.z),
  240.                 Quaternion.Euler(tree.rotation.x, tree.rotation.y, tree.rotation.z));
  241.  
  242.             treePrefab.transform.SetParent(EnvironmentManager.Instance.allTrees.transform);
  243.         }
  244.  
  245.         // Destroy animals that should not exist
  246.         foreach (Transform animalType in EnvironmentManager.Instance.allAnimals.transform)
  247.         {
  248.             foreach (Transform animal in animalType.transform)
  249.             {
  250.                 if (environmentData.animals.Contains(animal.gameObject.name) == false)
  251.                 {
  252.                     Destroy(animal.gameObject);
  253.                 }
  254.             }
  255.         }
  256.  
  257.         // Add storage Boxes
  258.         foreach (StorageData storage in environmentData.storage)
  259.         {
  260.             var storageBoxPrefab = Instantiate(Resources.Load<GameObject>("StorageBoxModel"),
  261.                 new Vector3(storage.position.x, storage.position.y, storage.position.z),
  262.                 Quaternion.Euler(storage.rotation.x, storage.rotation.y, storage.rotation.z));
  263.  
  264.             storageBoxPrefab.GetComponent<StorageBox>().items = storage.items;
  265.  
  266.             storageBoxPrefab.transform.SetParent(EnvironmentManager.Instance.placeables.transform);
  267.  
  268.  
  269.         }
  270.  
  271.  
  272.  
  273.     }
  274.  
  275.  
  276.  
  277.  
  278.  
  279.     private void SetPlayerData(PlayerData playerData)
  280.     {
  281.         // Setting Player Stats
  282.  
  283.         PlayerState.Instance.currentHealth = playerData.playerStats[0];
  284.         PlayerState.Instance.currentCalories = playerData.playerStats[1];
  285.         PlayerState.Instance.currentHydrationPercent = playerData.playerStats[2];
  286.  
  287.         // Setting Player Position
  288.  
  289.         Vector3 loadedPosition;
  290.         loadedPosition.x = playerData.playerPositionAndRotation[0];
  291.         loadedPosition.y = playerData.playerPositionAndRotation[1];
  292.         loadedPosition.z = playerData.playerPositionAndRotation[2];
  293.  
  294.         PlayerState.Instance.playerBody.transform.position = loadedPosition;
  295.  
  296.         // Setting Player Rotation
  297.  
  298.         Vector3 loadedRotation;
  299.         loadedRotation.x = playerData.playerPositionAndRotation[3];
  300.         loadedRotation.y = playerData.playerPositionAndRotation[4];
  301.         loadedRotation.z = playerData.playerPositionAndRotation[5];
  302.  
  303.         PlayerState.Instance.playerBody.transform.rotation = Quaternion.Euler(loadedRotation);
  304.        
  305.         // Setting the inventory content
  306.         foreach(string item in playerData.inventoryContent)
  307.         {
  308.             InventorySystem.Instance.AddToInventory(item);
  309.         }
  310.  
  311.         // Setting the quick slots content
  312.         foreach (string item in playerData.quickSlotsContent)
  313.         {
  314.             // Find next free quick slot
  315.             GameObject availableSlot = EquipSystem.Instance.FindNextEmptySlot();
  316.  
  317.             var itemToAdd = Instantiate(Resources.Load<GameObject>(item));
  318.  
  319.             itemToAdd.transform.SetParent(availableSlot.transform, false);
  320.         }
  321.  
  322.  
  323.        
  324.     }
  325.  
  326.     public void StartLoadedGame(int slotNumber)
  327.     {
  328.         ActivateLoadingScreen();
  329.  
  330.         isLoading = true;
  331.  
  332.         SceneManager.LoadScene("GameScene");
  333.  
  334.         StartCoroutine(DelayedLoading(slotNumber));
  335.     }
  336.  
  337.     private IEnumerator DelayedLoading(int slotNumber)
  338.     {
  339.  
  340.         yield return new WaitForSeconds(1f);
  341.  
  342.         LoadGame(slotNumber);
  343.     }
  344.  
  345.  
  346.     #endregion
  347.  
  348.  
  349.     #endregion
  350.  
  351.     #region || ---------- To Binary Section ---------- ||
  352.  
  353.     public void SaveGameDataToBinaryFile(AllGameData gameData, int slotNumber)
  354.     {
  355.         BinaryFormatter formatter = new BinaryFormatter();
  356.  
  357.  
  358.         FileStream stream = new FileStream(binaryPath + fileName + slotNumber + ".bin", FileMode.Create);
  359.  
  360.         formatter.Serialize(stream, gameData);
  361.         stream.Close();
  362.  
  363.         print("Data saved to" + binaryPath + fileName + slotNumber + ".bin");
  364.  
  365.     }
  366.  
  367.     public AllGameData LoadGameDataFromBinaryFile(int slotNumber)
  368.     {
  369.      
  370.  
  371.         if (File.Exists(binaryPath + fileName + slotNumber + ".bin"))
  372.         {
  373.             BinaryFormatter formatter = new BinaryFormatter();
  374.             FileStream stream = new FileStream(binaryPath + fileName + slotNumber + ".bin", FileMode.Open);
  375.  
  376.             AllGameData data = formatter.Deserialize(stream) as AllGameData;
  377.             stream.Close();
  378.  
  379.  
  380.             print("Data Loaded from" + binaryPath + fileName + slotNumber + ".bin");
  381.  
  382.  
  383.             return data;
  384.         }
  385.         else
  386.         {
  387.             return null;
  388.         }
  389.     }
  390.  
  391.     #endregion
  392.  
  393.     #region || ---------- To Json Section ---------- ||
  394.  
  395.     public void SaveGameDataToJsonFile(AllGameData gameData, int slotNumber)
  396.     {
  397.         string json = JsonUtility.ToJson(gameData);
  398.  
  399.         string encrypted = EncryptionDecryption(json);
  400.  
  401.         using (StreamWriter writer = new StreamWriter(jsonPathProject + fileName + slotNumber + ".json")) // SaveGame1.json
  402.         {
  403.                 writer.Write(encrypted);
  404.                 print("Saved Game to Json file at : " + jsonPathProject + fileName + slotNumber + ".json");
  405.         };
  406.     }
  407.  
  408.     public AllGameData LoadGameDataFromJsonFile(int slotNumber)
  409.     {
  410.         using (StreamReader reader = new StreamReader(jsonPathProject + fileName + slotNumber + ".json")) // SaveGame1.json
  411.         {
  412.             string json = reader.ReadToEnd();
  413.  
  414.             string decrypted = EncryptionDecryption(json);
  415.  
  416.             AllGameData data = JsonUtility.FromJson<AllGameData>(decrypted);
  417.             return data;
  418.         };
  419.  
  420.     }
  421.  
  422.  
  423.  
  424.  
  425.     #endregion
  426.  
  427.     #region || ---------- Settings Section ---------- ||
  428.  
  429.     #region || ---------- Volume Settings ---------- ||
  430.     [System.Serializable]
  431.     public class VolumeSettings
  432.     {
  433.         public float music;
  434.         public float effects;
  435.         public float master;
  436.     }
  437.  
  438.     public void SaveVolumeSettings(float _music, float _effects, float _master)
  439.     {
  440.         VolumeSettings volumeSettings = new VolumeSettings()
  441.         {
  442.             music = _music,
  443.             effects= _effects,
  444.             master = _master
  445.         };
  446.  
  447.         PlayerPrefs.SetString("Volume", JsonUtility.ToJson(volumeSettings));
  448.         PlayerPrefs.Save();
  449.  
  450.         print("Saved to Player Pref");
  451.     }
  452.  
  453.     public VolumeSettings LoadVolumeSettings()
  454.     {
  455.         return JsonUtility.FromJson<VolumeSettings>(PlayerPrefs.GetString("Volume"));
  456.     }
  457.     #endregion
  458.  
  459.  
  460.  
  461.     #endregion
  462.  
  463.     #region || ---------- Encryption ---------- ||
  464.    
  465.     public string EncryptionDecryption(string jsonString)
  466.     {
  467.         string keyword = "1234";
  468.  
  469.         string result = "";
  470.  
  471.         for (int i = 0; i < jsonString.Length; i++)
  472.         {
  473.             result += (char)(jsonString[i] ^ keyword[i % keyword.Length]);
  474.         }
  475.  
  476.         return result; // Encrypted or Decrypted String
  477.  
  478.  
  479.         // XOR = "is there a difference"
  480.  
  481.         // --- Encrypt --- \\
  482.         // Evelyn - 01000101 01110110 01100101 01101100 01111001 01101110
  483.         // E - 01000101
  484.         // Key - 00000001
  485.         //
  486.         // Encrypted - 01000100
  487.  
  488.         // --- Decrypt --- \\
  489.         // Encrypted - 01000100
  490.         // Key -       00000001
  491.         //
  492.         // M -         01000101
  493.  
  494.     }
  495.  
  496.  
  497.     #endregion
  498.  
  499.     #region || ---------- Loading Section ---------- ||
  500.  
  501.     public void ActivateLoadingScreen()
  502.     {
  503.         loadingScreen.gameObject.SetActive(true);
  504.  
  505.         Cursor.lockState = CursorLockMode.Locked;
  506.         Cursor.visible = false;
  507.  
  508.         // music for loading screen // SoundManager.Instance.PlaySound(SoundManager.Instance.startingZoneBGMusic);
  509.  
  510.         // animation
  511.  
  512.         // show
  513.     }
  514.  
  515.     public void DisableLoadingScreen()
  516.     {
  517.         loadingScreen.gameObject.SetActive(false);
  518.     }
  519.  
  520.  
  521.  
  522.     #endregion
  523.  
  524.     #region || ---------- Utility ---------- ||
  525.  
  526.     public bool DoesFileExists(int slotNumber)
  527.     {
  528.         if (isSavingToJson)
  529.         {
  530.             if (System.IO.File.Exists(jsonPathProject + fileName + slotNumber + ".json")) //SaveGame1.json
  531.             {
  532.                 return true;
  533.             }
  534.             else
  535.             {
  536.                 return false;
  537.             }
  538.         }
  539.         else
  540.         {
  541.             if (System.IO.File.Exists(binaryPath + fileName + slotNumber + ".bin")) //SaveGame1.bin
  542.             {
  543.                 return true;
  544.             }
  545.             else
  546.             {
  547.                 return false;
  548.             }
  549.         }
  550.     }
  551.  
  552.     public bool IsSlotEmpty(int slotNumber)
  553.     {
  554.         if (DoesFileExists(slotNumber))
  555.         {
  556.             return false;
  557.         }
  558.         else
  559.         {
  560.             return true;
  561.         }
  562.     }
  563.  
  564.  
  565.     public void DeselectButton()
  566.     {
  567.         GameObject myEventSystem = GameObject.Find("EventSystem");
  568.         myEventSystem.GetComponent<UnityEngine.EventSystems.EventSystem>().SetSelectedGameObject(null);
  569.     }
  570.  
  571.     #endregion
  572.  
  573. }
  574.  
Add Comment
Please, Sign In to add comment