Search Unity

Question saving to persistentdatapath not working

Discussion in 'Scripting' started by GoldenGemGames, May 29, 2023.

  1. GoldenGemGames

    GoldenGemGames

    Joined:
    Nov 24, 2019
    Posts:
    20
    Code (CSharp):
    1.     public class SaveScore : MonoBehaviour
    2.     {
    3.         public string saveName = "SavedScore";
    4.         public HighScore highScore;
    5.        
    6.         public void SavetoFile()
    7.         {
    8.             string path = Application.persistentDataPath;
    9.             if (!Directory.Exists(path))
    10.             {
    11.                 Directory.CreateDirectory(path);
    12.             }
    13.             BinaryFormatter formatter = new BinaryFormatter();
    14.             FileStream saveFile = File.Create(path + "/" + saveName + ".bin");
    15.             formatter.Serialize(saveFile, highScore);
    16.             saveFile.Close();
    17.             Debug.Log("File Saved");
    18.         }
    19.     }
    20.  
    21.  
    This method is triggered upon your lives becoming zero. the same routine that calls this method calls async to load the menu scene, on awake of the menu the loading method is called. In my console it'll print out the Debug shown above but when i go to that directory, no such folder is created and the loading method says the directory made by the save doesn't exist. Does anyone know what I did wrong here?
     
  2. Do not use
    BinaryFormatter
    , it will make your application vulnerable during deserialization.
    See Microsoft's own documentation here.

    Use BinaryReader and BinaryWriter instead (see examples how to use them).