We are trying to code a ‘Continue’ button in our Main Menu that would load the most recently created savegame, but is not always working (sometimes it does, sometimes not). Do you guys have any advice on how to proceed with this? Here’s our code so far:
//Savegames data
DirectoryInfo dirInfo = new DirectoryInfo(PlatformPath.GetPersistentPath());
if (dirInfo.Exists) {
FileInfo[] filesInfo = dirInfo.GetFiles ("SaveSlot*.sav");
if (filesInfo.Length == 0) {
DeactiveContinue ();
} else {
int selIndex = 0;
filesInfo[selIndex].Refresh();
for (int i = 0; i < filesInfo.Length; ++i) {
filesInfo[i].Refresh ();
if (filesInfo [i].CreationTime > filesInfo [selIndex].CreationTime)
selIndex = i;
}
continueFileName_ = filesInfo [selIndex].Name;
}
} else {
DeactiveContinue ();
}
Maybe the CreationTime property is not the most appropriate way to check this, but we are not sure.
When it doesn’t work, which one does it select? Is there a pattern to this wrong selection?
Have you printed out the creation times and confirmed they’ve come back correct?
Are you overwriting existing files, or modifying existing files, when subsequently saving them… and then expecting CreationTime to update, where as it doesn’t, because it records the time that the file was created, not last modified (LastWriteTime).
Also, usually you should use ‘UTC’ time when comparing times, to ensure that you have a real difference in time. This is more of a “always use your blinkers” type thing, as in this local system they SHOULD be in the same timezone and what not. But it’s a habit you should maintain either way when dealing with dates.
Depending on how you’re testing (and which OS) there is also the issue of “tunnelling” which is [quote]
…is a feature of NT based systems wherein a new file with the same name as a recently deleted file in the same directory will inherit the creation time of the old file.
[/quote]
It’s a fairly short time frame (30 seconds-ish maybe?), but is a potential issue depending on how you’re testing things. You can eliminate the issue by explicitly setting the create date on the file when you save it.
Why not write to file which save file was used last? That’ll prevent you from having to check system timestamps.
So whenever your player loads a save game, just put that save game into a save-metadata file you’ve made. That’s the appropriate one.
An obvious bug that will show up with LastWriteTime is that unless you immediately make a change to a save game when you load it, it won’t be the one that shows up in Continue unless the player does something that triggers you to save to file. So if the player loads a game, and then immediately quits, that won’t be the game that shows up under continue. It’s a small issue, but it’s still not necessary.