How to save/load file using Google play services

Google play services offer a lot of services like leaderboard, achievements, events and save games. In this tutorial, we will see how to use Google play services to save and load your games

Prerequisites

Read the tutorials below before proceeding

  1. Setup Google play service in Unity.
  2. Create a serializable class.
  3. Convert the class to Json file.

We will start the tutorial with simple steps

Enable saved games

Go to Google play console and open up the Play games services tab on the left pane.

Free Unity asset banner

Click Setup and Management>Configuration. Click on Edit properties.

Scroll down and Switch on saved games. Remember it cannot be switched off once turned on and published.

You need to enable saved games in your code too.

Add “using GooglePlayGames.BasicApi.SavedGame;” to your script and change the configuration in the Awake function in the Play games sign in tutorial to the code below.

 PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.EnableSavedGames()
.Build();

Saving and loading data from play services

Hope you have gone through the Json tutorial on how to convert your serializable class to Json and back. If not, you should go back and complete that tutorial before proceeding.

The save process is described in the image below for better understanding

Let’s dig into the code

To create or open a file

if(Social.Active.localUser.authenticated)
{
  ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(Filename,
                 DataSource.ReadCacheOrNetwork,
                 ConflictResolutionStrategy.UseLongestPlaytime,
                 runsavefunction);
}else
{
Debug.Log("Not authenticated!");
}

If file creation was successful then save data to cloud

private void runsavefunction(SavedGameRequestStatus status, ISavedGameMetadata game) {
         //check success
         if (status == SavedGameRequestStatus.Success){
             
                 
                 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(yourJsondata);
                 //create builder. here you can add play time, time created etc for UI.
                 SavedGameMetadataUpdate.Builder builder = new SavedGameMetadataUpdate.Builder();
                 SavedGameMetadataUpdate updatedMetadata = builder.Build();//you can add description to save file here
                 //saving to cloud
                 ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game, updatedMetadata, bytes, feedback);            
             
         } else {
             Debug.LogWarning("Error opening game: " + status);
         }
     }
private void feedback(SavedGameRequestStatus status, ISavedGameMetadata game) {
         if (status == SavedGameRequestStatus.Success){
             Debug.Log("Game " + game.Description + " written");
         } else {
             Debug.LogWarning("Error saving game: " + status);
         }
     }

Loading also requires you to open the file so you can use the code above and add a Boolean to check if you are saving or loading the data. Here is the loading script

bool saving=false;
if(Social.Active.localUser.authenticated)
{
   saving=true;//set this if you going to save the game;
  ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(Filename,
                 DataSource.ReadCacheOrNetwork,
                 ConflictResolutionStrategy.UseLongestPlaytime,
                 runsavefunction);
}else
{
Debug.Log("Not authenticated!");
}
private void runsavefunction(SavedGameRequestStatus status, ISavedGameMetadata game) {
         //check success
         if (status == SavedGameRequestStatus.Success){
                 if(saving)
                 {   
                 //save game code in the above snipped goes here           
                 } else//loading
                   {
                    ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game, Load_feedback);
                   }
                    
         } else {
             Debug.LogWarning("Error opening game: " + status);
         }
     }
private void Load_feedback(SavedGameRequestStatus status, byte[] data) {
         if (status == SavedGameRequestStatus.Success){
             Debug.Log("SaveGameLoaded, success=" + status);
             string json_Data=System.Text.Encoding.UTF8.GetString(data);//convert Json to class as shown in the previous tutorial.
         } else {
             Debug.LogWarning("Error reading game: " + status);
         }
     }

Now you have saved your game data to Google saved games and loaded it back. If you have any other questions leave it in the comment section below.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.