I have a game with a home “Camp” that players spend a long time in, and I want to save any progress they make without having to write out save files after every single action, since that could be up to 1 time per second.
Here is how save currently works in my game:
- If the player exits camp, a save is kicked off. This works fine, as the game is still running.
- If the app suspends (multitask, phone call, etc) Unity gets the OnApplicationPause event, and in this case, I also kick off a Save. This is important because the app can go into the background, and may get wiped from memory.
- When saving initiates, I manually write out save files in binary using EZ Save. They are written to a temporary location. There are only a few files to write, and the total size is pretty small, less than 50 kb.
- If there were no errors during writing the save files, then they are copied from the temp location to the real location.
This actually works the vast majority of the time. On iOS, it is nearly flawless. On Android, there is an occasional problem.
The Problem:
- On rare occasions, the player ends up with one or more of the files in the save being truncated. The beginning of a file is written, and at some point, the rest is cut off. The player’s game is corrupted.
- My speculation on what happens is that the game is copying over save files from the temp location to the proper location, and the OS decides, “Okay, that’s enough time, I’m shutting you down,” or “I need your memory, stop whatever you’re doing.”
Questions:
- Is there any way to guarantee that I can write out a save file on suspend without being interrupted?
- Is there something else I should be doing to guarantee all data gets saved, but without potential for corruption?
- Is there any kind of atomic file copy I could use, something that can’t be interrupted?
Any help or advice is appreciated!