Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by BerenBotje · Sep 04, 2019 at 05:49 PM · savingsave dataexceptionbinaryformatterbackup

Is this code handling fall back on previous saves upon failure the right way?

  1. How can I detect if the saving process was interrupted (mobile ran out of battery during saving etc.)?

  2. How can I then fall back on the previous save file that wasn't interrupted or something?
    I'am using a binary file to save to two locations. As u can see I'am using a boolean in catch to determine if there happened any exceptions during saving, then I can use this boolean to determine if I can load data from the file. But I don't know if this is the way to go for mobile.

      public static class SaveSystem1 {
    
    
              static bool ErrorSavingPath = false;
    
              static bool ErrorSavingPath1 = false;
    
        
             public static void SavePlayer(Player player)
             {
                 BinaryFormatter formatter = new BinaryFormatter();
                 string path = Path.Combine(Application.persistentDataPath, "location.toSave");
                 string path1 = Path.Combine(Application.persistentDataPath, "location.toSave1");
                 if (path != null)
                 {
                     
                     FileStream stream = new FileStream(path, FileMode.Create);
                     try
                     {
                         PlayerData data = new PlayerData(player);
         
                         formatter.Serialize(stream, data);
                     }
                     catch (System.Exception ex)
                     {
                         Debug.Log(ex);
                         Debug.Log(ex.Message);
                         Debug.Log(ex.StackTrace);
                         ErrorSavingPath = true; //This is the were I check if saving went well...
                     }
         
                     finally
                     {
                         stream.Close();
                     }
         
                 }
         
                 if (path1 != null)
                 {// same as before but with path1 instead}
         
         
          public static PlayerData LoadPlayer()
             {
                 string path = Path.Combine(Application.persistentDataPath, "location.toSave");
                 string path1 = Path.Combine(Application.persistentDataPath, "location.toSave1");
         
                 if (File.Exists(path) && !ErrorSavingPath){// load from well saved path, reset bool etc.
         
                 {
         
     
    
    
    
    
    
    
    
    
    
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by Meishin · Sep 06, 2019 at 11:28 AM

Hi @BerenBotje,

Saving twice in a row is useless, it's most probable that if the 1st save fail, the 2nd will also fail.

Instead make a little "saves manager" that keeps track of the last N successful saves (and delete olders). If a save failed and you need to load then your "Saves Manager" will load the last successful save.

To detect if your function has completed until it's last byte, return True at the end of the function, something like that ;

 public static class SaveSystem
 {
     private const string configpath = "path to your saving config that you initially created with playerpref, json, whatever";
     private static List<Save> saves = SavesInitializer();
     private static long lastNbUnique;
     private const string savesfolderpath = "dd";
 
     private static List<Save> SavesInitializer()
     {
         List<Save> output = new List<Save>();
 
         // Initialize output by reading config saves folder 
         // (that you initially created with playerpref, json, whatever)
         // Initialize lastNbUnique to be the Highest of any of your saves +1
 
         return output;
     }
 
     public static bool SavePlayer(Player player)
     {
         Save NewSave = new Save(savesfolderpath, lastNbUnique, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
         lastNbUnique += 1;
         saves.Add(NewSave);
         
         // Initialize your thing
         try
         {
             // Do your thing
             NewSave.Success = true;
             return true;
         }
         catch ()
         {
             // Do your thing
             NewSave.LogError = "error";
             return false;
         }
     }
     
     // For load :
     // Get latest Save.NbUnique
     // Load it
 
 }
 
 public class Save
 {
     public string Path;
     public bool Success;
     public long NbUnique;
     // Optional but nice to have to debug what went wrong
     public string LogError;
     public string Date;
 
     public Save(string _path, long _nbUnique, string _date, bool _success=false, string _logError=null)
     {
     Path = _path;
     Success = _success;
     NbUnique = _nbUnique;
     LogError = _logError;
     Date = _date;
     }
 }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BerenBotje · Sep 06, 2019 at 04:56 PM 0
Share

Sry but what does private static List saves = SavesInitializer(); do? @$$anonymous$$eishin

avatar image
0

Answer by BerenBotje · Sep 07, 2019 at 04:24 PM

I this also good? I have used ur bool as return type in the saving method. I'am now saving only ones per call and overriding the oldest file. If I don't decide to delete one then there will be 2 files is that a problem? I am not saving that much and maybe its a good backup if the user deletes accidentally one file. Even though my methods contain more code after collapsing them it looks readable and it shouldn't run slower. Instead of the increment I used a boolean. @Meishin

 public static class SaveSystem4
 {
     static bool succesSave = false;
     static bool canSaveToPath1 = false;
 
    static public void SavingLogic(Player1 player) 
     {
         
         if( !canSaveToPath1)
         {
             succesSave = SavePlayer(player);
 
             if (succesSave)
             {
                 canSaveToPath1 = true;
             }
         }
 
         if ( canSaveToPath1)
         {
             succesSave = SavePlayer1(player);
 
             if (succesSave)
                 {
                     canSaveToPath1 = false;
                 } 
         }
     }
 static public PlayerData1 LoadingLogic()
 {
     if (canSaveToPath1)
     {
         return LoadPlayer();
     }
     return LoadPlayer1();
 }

     public static bool SavePlayer(Player1 player)...
     public static PlayerData1 LoadPlayer()...
 
     public static bool SavePlayer1(Player1 player)...//only path changed
     public static PlayerData1 LoadPlayer1()...
 
 }
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

112 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to save list of Sprites? 1 Answer

Initialize List in User Data Class without deleting binary file 0 Answers

Loading a serialized file after changing the adding a new var to it 2 Answers

[Android] Save data loss with PlayerPrefs? 2 Answers

Why am I getting SerializationException: Type 'UnityEngine.MonoBehaviour' etc. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges