Save Games
CP Social supports cloud savegames for all platforms
To be able to use save games you need an instance of the ICP_CloudSaveService
. An instance of this can be obtained from the CP_Social
class. But only after the user has been authenticated.
To make sure the user is always authenticated when trying to get the instance of the cloud save service. You can use the following example:
private ICP_CloudSaveService _cloudSaveService;
//Unity Start
void Start()
{
CP_Social.Authenticated += result =>
{
if (result.success)
{
_cloudSaveService = CP_Social.GetCloudSaveService();
}
};
}
Using this, the user will always be authenticated when trying to get the cloudsave service from CP Social.
Saving game data
After getting an instance of ICP_CloudSaveService
you can start saving games.
The first step in saving a game is getting or creating the metadata for that savegame, to get/create this metadata you can use the following example to retreive it from CP Social:
public void SaveGame(string saveName, byte[] gameData)
{
if (CP_Social.isAuthenticated)
{
_cloudSaveService.GetOrCreateSaveGameMetaData(saveName, result =>
{
if (result.success)
{
Debug.Log("Created saveGameMetaData: " + result.value.saveName);
ICP_SaveGameMetaData saveGameMetaData = result.value;
//'SaveGame' can be found in the next code snippit
SaveGame(saveGameMetaData, byte[] gameData);
}
else
{
Debug.LogError("Could not create SaveGameMetaData: " + result.errorMessage);
}
});
}
}
}
After getting the metadata you can save your game data:
private void SaveGame(ICP_SaveGameMetaData metaData, byte[] gameData)
{
if (CP_Social.isAuthenticated)
{
_cloudSaveService.SaveGameData(metaData, gameData, result =>
{
Debug.Log("Saved gamedata: " + result.success);
});
}
}
After doing all of this your game will be save to the cloud of the current target platform.
Loading game data
Loading game data uses the same metadata concept as saving a game, first you'll need to get the metadata for the save game using the name of the save
public void LoadGame(string saveName, Action<byte[]> callback)
{
if (CP_Social.isAuthenticated)
{
_cloudSaveService.GetOrCreateSaveGameMetaData(saveName, result =>
{
if (result.success)
{
Debug.Log("Created saveGameMetaData: " + result.value.saveName);
ICP_SaveGameMetaData saveGameMetaData = result.value;
//'LoadSave' can be found in the next code snippit
LoadSave(saveGameMetaData, callback);
}
else
{
Debug.LogError("Could not create SaveGameMetaData: " + result.errorMessage);
}
});
}
}
}
After getting the metadata you can load your game data:
private void LoadSave(ICP_SaveGameMetaData metaData, Action<byte[]> callback)
{
if (CP_Social.isAuthenticated)
{
_cloudSaveService.LoadGameData(metaData, result =>
{
if (result.success)
{
byte[] data = result.value.data;
callback(data);
}
else
{
Debug.LogError(result.errorMessage);
}
});
}
}
The final callback will be called from CP Social on the main thread, so no worries about having to sync the callback, this will be done for you.