-
-
Notifications
You must be signed in to change notification settings - Fork 556
Saving and Loading
As soon as you enable menus, it is expected that you also implement how your game handles saving and loading. So, in a sense saving / loading is turned on and off along with the menu. This limitation is likely to be addressed in the future, as it is possible that a game can have a menu but no saving / loading system.
The interaction between the user and the game is already present as part of the menu. So all that remains to be done is to implement what happens when the user saves / loads.
The saving process is handled by overriding the following method.
In essence, we capture the state of the game that needs to be saved into a serializable object, say data
. For example, com.almasb.easyio.serialization.Bundle
, which acts as a container where you can store other Bundle
objects.
@Override
public DataFile saveState() {
// save state into `data`
Serializable data = ...
return new DataFile(data);
}
Having done that, we wrap data
with a DataFile
, which provides meta information like timestamp, version, etc.
This information is then used to find / sort / validate save files during loading.
Intuitively, the loading process is the reverse of saving.
The loading is handled by overriding the following method, which takes DataFile
as a parameter.
As you might've guessed, this is the same object that you returned in the previous method during the saving process.
@Override
public void loadState(DataFile dataFile) {
// SomeType is the actual type of the object serialized
// e.g. String, Bundle, HashMap, etc.
SomeType data = (SomeType) dataFile.getData();
// do something with `data`
}
From the dataFile
object you can readily obtain your data
and then use it to load the game state.
This is all there is to the saving / loading system.
Everything else will be seamlessly provided by the framework.
A sample that shows how to use the saving / loading system can be seen here.