I’m currently working on a multiplayer game that requires player attributes and preferences to be saved to an external online database. I’ve heard a few people mention a NoSQL object database method over MySQL but for the time being my web hosting’s MySQL database will suffice.
Anyway, my question is regarding intervals at which the game saves the users state (position, experience, level, currency, etc) to the database. My initial thoughts where to do this every so many seconds (any insight onto a feasible time interval to do this would be much appreciated, at the moment its just every 10 seconds for testing), on logout and on application close. Logout is fine, when they click a button, save the state, however I’m struggling to figure out how to save the state on close.
At the moment my save state script contains an OnApplicationQuit method which works and calls my save state function. The problem is that the function utilises a WWW object inside a Coroutine, this takes a little time to complete and the application closes before the state of the character can be saved. Is there a way to postpone quit until the WWW object has successfully saved the changes? Or is there another option you would recommend?
OnApplicationQuit is merely a callback, and unfortunately you cannot reliably run any delayed logic in it. As you would run into a similar problem in an accidental exit (i.e. a crash) I would concur with the interval idea. What I would recommend would be to register significant data changes to a listener class that will stock pile these delta changes until the interval is reached, then at the interval check to see if it has new data. This way it will contact the database no more often than the interval you set, while also skipping a round if no new data is available, this way you aren’t needlessly contacting your database when there are no significant changes. You will occasionally lose data (if a player accomplishes something just before a crash) but you can tweak your interval to minimize the impact. As long as the player doesn’t lose more than a couple minutes of progress they likely won’t get upset.
Example:
Interval set to 2 minutes
After 1 minute the player accomplishes something significant (got a new weapon) this is registered to the listener class. Database is not called.
After 1 Miunte and 45 seconds player gets 500 gold, this is registered to the class. Database is not called.
2 Minute mark, Listener class sees that it has data and we save the new weapon and gold to the database.
nothing happens for the next 2 minutes
4 minute mark, Listener class sees that it does -not- have data and does -not- contact database
4 minutes and 20 seconds, player earns 200 gold
4 minutes and 25 seconds, program crashes
Player reboots game, they still have their weapon and the 500 gold, but not the 200