evelynshilosky

SaveManager - Part 26

Nov 17th, 2023 (edited)
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.43 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.  
  54.     #region || ---------- Saving ---------- ||
  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.         return new EnvironmentData(itemsPickedup);
  71.     }
  72.  
  73.     private PlayerData GetPlayerData()
  74.     {
  75.         float[] playerStats = new float[3];
  76.         playerStats[0] = PlayerState.Instance.currentHealth;
  77.         playerStats[1] = PlayerState.Instance.currentCalories ;
  78.         playerStats[2] = PlayerState.Instance.currentHydrationPercent;
  79.  
  80.         float[] playerPosAndRot = new float[6];
  81.         playerPosAndRot[0] = PlayerState.Instance.playerBody.transform.position.x;
  82.         playerPosAndRot[1] = PlayerState.Instance.playerBody.transform.position.y;
  83.         playerPosAndRot[2] = PlayerState.Instance.playerBody.transform.position.z;
  84.  
  85.         playerPosAndRot[3] = PlayerState.Instance.playerBody.transform.rotation.x;
  86.         playerPosAndRot[4] = PlayerState.Instance.playerBody.transform.rotation.y;
  87.         playerPosAndRot[5] = PlayerState.Instance.playerBody.transform.rotation.z;
  88.  
  89.         string[] inventory = InventorySystem.Instance.itemList.ToArray();
  90.  
  91.         string[] quickSlots = GetQuickSlotsContent();
  92.  
  93.         return new PlayerData(playerStats, playerPosAndRot, inventory, quickSlots);
  94.  
  95.     }
  96.  
  97.     private string[] GetQuickSlotsContent()
  98.     {
  99.         List<string> temp = new List<string>();
  100.  
  101.         foreach (GameObject slot in EquipSystem.Instance.quickSlotsList)
  102.         {
  103.             if (slot.transform.childCount != 0)
  104.             {
  105.                 string name = slot.transform.GetChild(0).name;
  106.                 string str2 = "(Clone)";
  107.                 string cleanName = name.Replace(str2, "");
  108.                 temp.Add(cleanName);
  109.             }
  110.         }
  111.  
  112.         return temp.ToArray();
  113.     }
  114.  
  115.     public void SavingTypeSwitch(AllGameData gameData, int slotNumber)
  116.     {
  117.         if (isSavingToJson)
  118.         {
  119.             SaveGameDataToJsonFile(gameData, slotNumber);
  120.         }
  121.         else
  122.         {
  123.             SaveGameDataToBinaryFile(gameData, slotNumber);
  124.         }
  125.     }
  126.     #endregion
  127.  
  128.     #region || ---------- Loading ---------- ||
  129.  
  130.     public AllGameData LoadingTypeSwitch(int slotNumber)
  131.     {
  132.         if (isSavingToJson)
  133.         {
  134.             AllGameData gameData = LoadGameDataFromJsonFile(slotNumber);
  135.             return gameData;
  136.         }
  137.         else
  138.         {
  139.             AllGameData gameData = LoadGameDataFromBinaryFile(slotNumber);
  140.             return gameData;
  141.         }
  142.     }
  143.  
  144.     public void LoadGame(int slotNumber)
  145.     {
  146.         // Player Data
  147.         SetPlayerData(LoadingTypeSwitch(slotNumber).playerData);
  148.  
  149.         // Environment Data
  150.         SetEnvironmentData(LoadingTypeSwitch(slotNumber).environmentData);
  151.  
  152.          isLoading = false;
  153.  
  154.         DisableLoadingScreen();
  155.     }
  156.  
  157.     private void SetEnvironmentData(EnvironmentData environmentData)
  158.     {
  159.         foreach (Transform itemType in EnvironmentManager.Instance.allItems.transform)
  160.         {
  161.             foreach (Transform item in itemType.transform)
  162.             {
  163.                 if (environmentData.pickedupItems.Contains(item.name))
  164.                 {
  165.                     Destroy(item.gameObject);
  166.                 }
  167.  
  168.             }
  169.  
  170.  
  171.         }
  172.  
  173.         // So the itemsPickedup will be persistant.
  174.         InventorySystem.Instance.itemsPickedup = environmentData.pickedupItems;
  175.  
  176.     }
  177.  
  178.  
  179.  
  180.  
  181.  
  182.     private void SetPlayerData(PlayerData playerData)
  183.     {
  184.         // Setting Player Stats
  185.  
  186.         PlayerState.Instance.currentHealth = playerData.playerStats[0];
  187.         PlayerState.Instance.currentCalories = playerData.playerStats[1];
  188.         PlayerState.Instance.currentHydrationPercent = playerData.playerStats[2];
  189.  
  190.         // Setting Player Position
  191.  
  192.         Vector3 loadedPosition;
  193.         loadedPosition.x = playerData.playerPositionAndRotation[0];
  194.         loadedPosition.y = playerData.playerPositionAndRotation[1];
  195.         loadedPosition.z = playerData.playerPositionAndRotation[2];
  196.  
  197.         PlayerState.Instance.playerBody.transform.position = loadedPosition;
  198.  
  199.         // Setting Player Rotation
  200.  
  201.         Vector3 loadedRotation;
  202.         loadedRotation.x = playerData.playerPositionAndRotation[3];
  203.         loadedRotation.y = playerData.playerPositionAndRotation[4];
  204.         loadedRotation.z = playerData.playerPositionAndRotation[5];
  205.  
  206.         PlayerState.Instance.playerBody.transform.rotation = Quaternion.Euler(loadedRotation);
  207.        
  208.         // Setting the inventory content
  209.         foreach(string item in playerData.inventoryContent)
  210.         {
  211.             InventorySystem.Instance.AddToInventory(item);
  212.         }
  213.  
  214.         // Setting the quick slots content
  215.         foreach (string item in playerData.quickSlotsContent)
  216.         {
  217.             // Find next free quick slot
  218.             GameObject availableSlot = EquipSystem.Instance.FindNextEmptySlot();
  219.  
  220.             var itemToAdd = Instantiate(Resources.Load<GameObject>(item));
  221.  
  222.             itemToAdd.transform.SetParent(availableSlot.transform, false);
  223.         }
  224.  
  225.  
  226.        
  227.     }
  228.  
  229.     public void StartLoadedGame(int slotNumber)
  230.     {
  231.         ActivateLoadingScreen();
  232.  
  233.         isLoading = true;
  234.  
  235.         SceneManager.LoadScene("GameScene");
  236.  
  237.         StartCoroutine(DelayedLoading(slotNumber));
  238.     }
  239.  
  240.     private IEnumerator DelayedLoading(int slotNumber)
  241.     {
  242.  
  243.         yield return new WaitForSeconds(1f);
  244.  
  245.         LoadGame(slotNumber);
  246.     }
  247.  
  248.  
  249.     #endregion
  250.  
  251.  
  252.     #endregion
  253.  
  254.     #region || ---------- To Binary Section ---------- ||
  255.  
  256.     public void SaveGameDataToBinaryFile(AllGameData gameData, int slotNumber)
  257.     {
  258.         BinaryFormatter formatter = new BinaryFormatter();
  259.  
  260.  
  261.         FileStream stream = new FileStream(binaryPath + fileName + slotNumber + ".bin", FileMode.Create);
  262.  
  263.         formatter.Serialize(stream, gameData);
  264.         stream.Close();
  265.  
  266.         print("Data saved to" + binaryPath + fileName + slotNumber + ".bin");
  267.  
  268.     }
  269.  
  270.     public AllGameData LoadGameDataFromBinaryFile(int slotNumber)
  271.     {
  272.      
  273.  
  274.         if (File.Exists(binaryPath + fileName + slotNumber + ".bin"))
  275.         {
  276.             BinaryFormatter formatter = new BinaryFormatter();
  277.             FileStream stream = new FileStream(binaryPath + fileName + slotNumber + ".bin", FileMode.Open);
  278.  
  279.             AllGameData data = formatter.Deserialize(stream) as AllGameData;
  280.             stream.Close();
  281.  
  282.  
  283.             print("Data Loaded from" + binaryPath + fileName + slotNumber + ".bin");
  284.  
  285.  
  286.             return data;
  287.         }
  288.         else
  289.         {
  290.             return null;
  291.         }
  292.     }
  293.  
  294.     #endregion
  295.  
  296.     #region || ---------- To Json Section ---------- ||
  297.  
  298.     public void SaveGameDataToJsonFile(AllGameData gameData, int slotNumber)
  299.     {
  300.         string json = JsonUtility.ToJson(gameData);
  301.  
  302.         //string encrypted = EncryptionDecryption(json);
  303.  
  304.         using (StreamWriter writer = new StreamWriter(jsonPathProject + fileName + slotNumber + ".json")) // SaveGame1.json
  305.         {
  306.                 writer.Write(json);
  307.                 print("Saved Game to Json file at : " + jsonPathProject + fileName + slotNumber + ".json");
  308.         };
  309.     }
  310.  
  311.     public AllGameData LoadGameDataFromJsonFile(int slotNumber)
  312.     {
  313.         using (StreamReader reader = new StreamReader(jsonPathProject + fileName + slotNumber + ".json")) // SaveGame1.json
  314.         {
  315.             string json = reader.ReadToEnd();
  316.  
  317.             //string decrypted = EncryptionDecryption(json);
  318.  
  319.             AllGameData data = JsonUtility.FromJson<AllGameData>(json);
  320.             return data;
  321.         };
  322.  
  323.     }
  324.  
  325.  
  326.  
  327.  
  328.     #endregion
  329.  
  330.     #region || ---------- Settings Section ---------- ||
  331.  
  332.     #region || ---------- Volume Settings ---------- ||
  333.     [System.Serializable]
  334.     public class VolumeSettings
  335.     {
  336.         public float music;
  337.         public float effects;
  338.         public float master;
  339.     }
  340.  
  341.     public void SaveVolumeSettings(float _music, float _effects, float _master)
  342.     {
  343.         VolumeSettings volumeSettings = new VolumeSettings()
  344.         {
  345.             music = _music,
  346.             effects= _effects,
  347.             master = _master
  348.         };
  349.  
  350.         PlayerPrefs.SetString("Volume", JsonUtility.ToJson(volumeSettings));
  351.         PlayerPrefs.Save();
  352.  
  353.         print("Saved to Player Pref");
  354.     }
  355.  
  356.     public VolumeSettings LoadVolumeSettings()
  357.     {
  358.         return JsonUtility.FromJson<VolumeSettings>(PlayerPrefs.GetString("Volume"));
  359.     }
  360.     #endregion
  361.  
  362.  
  363.  
  364.     #endregion
  365.  
  366.     #region || ---------- Encryption ---------- ||
  367.    
  368.     public string EncryptionDecryption(string jsonString)
  369.     {
  370.         string keyword = "142759638";
  371.  
  372.         string result = "";
  373.  
  374.         for (int i = 0; i < jsonString.Length; i++)
  375.         {
  376.             result += (char)(jsonString[i] ^ keyword[i % keyword.Length]);
  377.         }
  378.  
  379.         return result; // Encrypted or Decrypted String
  380.  
  381.  
  382.         // XOR = "is there a difference"
  383.  
  384.         // --- Encrypt --- \\
  385.         // Evelyn - 01000101 01110110 01100101 01101100 01111001 01101110
  386.         // E - 01000101
  387.         // Key - 00000001
  388.         //
  389.         // Encrypted - 01000100
  390.  
  391.         // --- Decrypt --- \\
  392.         // Encrypted - 01000100
  393.         // Key -       00000001
  394.         //
  395.         // M -         01000101
  396.  
  397.     }
  398.  
  399.  
  400.     #endregion
  401.  
  402.     #region || ---------- Loading Section ---------- ||
  403.  
  404.     public void ActivateLoadingScreen()
  405.     {
  406.         loadingScreen.gameObject.SetActive(true);
  407.  
  408.         Cursor.lockState = CursorLockMode.Locked;
  409.         Cursor.visible = false;
  410.  
  411.         // music for loading screen // SoundManager.Instance.PlaySound(SoundManager.Instance.startingZoneBGMusic);
  412.  
  413.         // animation
  414.  
  415.         // show
  416.     }
  417.  
  418.     public void DisableLoadingScreen()
  419.     {
  420.         loadingScreen.gameObject.SetActive(false);
  421.     }
  422.  
  423.  
  424.  
  425.     #endregion
  426.     #region || ---------- Utility ---------- ||
  427.  
  428.     public bool DoesFileExists(int slotNumber)
  429.     {
  430.         if (isSavingToJson)
  431.         {
  432.             if (System.IO.File.Exists(jsonPathProject + fileName + slotNumber + ".json")) //SaveGame1.json
  433.             {
  434.                 return true;
  435.             }
  436.             else
  437.             {
  438.                 return false;
  439.             }
  440.         }
  441.         else
  442.         {
  443.             if (System.IO.File.Exists(binaryPath + fileName + slotNumber + ".bin")) //SaveGame1.bin
  444.             {
  445.                 return true;
  446.             }
  447.             else
  448.             {
  449.                 return false;
  450.             }
  451.         }
  452.     }
  453.  
  454.     public bool IsSlotEmpty(int slotNumber)
  455.     {
  456.         if (DoesFileExists(slotNumber))
  457.         {
  458.             return false;
  459.         }
  460.         else
  461.         {
  462.             return true;
  463.         }
  464.     }
  465.  
  466.  
  467.     public void DeselectButton()
  468.     {
  469.         GameObject myEventSystem = GameObject.Find("EventSystem");
  470.         myEventSystem.GetComponent<UnityEngine.EventSystems.EventSystem>().SetSelectedGameObject(null);
  471.     }
  472.  
  473.     #endregion
  474. }
  475.  
Add Comment
Please, Sign In to add comment