Game Development Reference
In-Depth Information
for (auto& serializable : m_serializables)
{
Serializable* pSerializable = serializable.second;
file << pSerializable->GetId();
file << std::endl;
pSerializable->OnSave(file);
file << std::endl;
file << std::endl;
}
}
An
ofstream
object is initialized by passing it the file name you wish to write to. You can then use the
standard
<<
operator to write data to the file. The o in
ofstream
stands for output, the f for file, and
stream for its ability to stream data, meaning we are working with an
output file stream
.
The
Save
method begins by writing out a
true
. This
bool
is used to determine if the save game has
a reinstatable save game inside. We write out
false
later when the player has completed the game.
Save
then loops over all of the stored
Serializable
objects, writes out their unique ID, and calls the
OnSave
method. The
std::endl
is being written out just to make the text file a little more readable
and easier to debug.
The opposite action to
Save
is
Load
, shown in Listing 24-4.
Listing 24-4. The
SerializationManager::Load
Method
bool SerializationManager::Load()
{
std::ifstream file{ m_filename };
bool found = file.is_open();
if (found)
{
bool isValid;
file >> isValid;
if (isValid)
{
std::cout <<
"Save game found, would you like to load? (Type yes to load)"
<< std::endl << std::endl;
std::string shouldLoad;
std::cin >> shouldLoad;
if (shouldLoad == "yes")
{
while (!file.eof())
{
unsigned int serializableId{ 0 };
file >> serializableId;
auto iter = m_serializables.find(serializableId);