Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Google Play Games Plugin Save/Load

Discussion in 'Android' started by el_saq, Feb 12, 2015.

  1. el_saq

    el_saq

    Joined:
    Feb 6, 2015
    Posts:
    7
    I´m using official plugin:

    https://github.com/playgameservices/play-games-plugin-for-unity

    I have this code for saving and loading:

    Code (CSharp):
    1.     System.Action<bool> mAuthCallback;
    2.    
    3.     GameData slot0;
    4.    
    5.     bool mSaving;
    6.     private Texture2D mScreenImage;
    7.    
    8.     // Use this for initialization
    9.     void Start () {
    10.        
    11.         slot0 = new GameData("New game");
    12.         mAuthCallback = (bool success) => {
    13.            
    14.             if (success) {
    15.                 Debug.Log("Authentication was successful!");
    16.                 slot0.State = "Click load or save";
    17.             }
    18.             else {
    19.                 Debug.LogWarning("Authentication failed!");
    20.             }
    21.            
    22.         };
    23.        
    24.        
    25.         PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
    26.             .EnableSavedGames()
    27.                 .Build();
    28.         PlayGamesPlatform.InitializeInstance(config);
    29.        
    30.         // Activate the Play Games platform. This will make it the default
    31.         // implementation of Social.Active
    32.         PlayGamesPlatform.Activate();
    33.        
    34.         // enable debug logs (note: we do this because this is a sample; on your production
    35.         // app, you probably don't want this turned on by default, as it will fill the user's
    36.         // logs with debug info).
    37.         PlayGamesPlatform.DebugLogEnabled = true;
    38.        
    39.         //Login explicitly for this sample, usually this would be silent
    40.         PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
    41.        
    42.        
    43.     }
    44.    
    45.     public void CaptureScreenshot() {
    46.         mScreenImage = new Texture2D(Screen.width, Screen.height);
    47.         mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
    48.         mScreenImage.Apply();
    49.     }
    50.  
    51.     // Save Button
    52.  
    53.     public void SaveButton ()
    54.     {
    55.         int idx = slot0.Data.IndexOf("_");
    56.         if (idx > 0) {
    57.             int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
    58.             val++;
    59.             slot0.Data = "Save_" + val;
    60.         }
    61.         else {
    62.             slot0.Data = "Save_0";
    63.         }
    64.         mSaving = true;
    65.         CaptureScreenshot();
    66.         ((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
    67.                                                                            4,true,true,SavedGameSelected);
    68.     }
    69.  
    70.     // Load Button
    71.  
    72.     public void LoadButton ()
    73.     {
    74.         mSaving = false;
    75.         ((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
    76.                                                                            4,false,false,SavedGameSelected);
    77.     }
    78.    
    79.    
    80.     public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
    81.        
    82.         if (status == SelectUIStatus.SavedGameSelected) {
    83.             string filename = game.Filename;
    84.             Debug.Log("opening saved game:  " + game);
    85.             if(mSaving && (filename == null || filename.Length == 0)) {
    86.                 filename = "save" + DateTime.Now.ToBinary();
    87.             }
    88.             if (mSaving) {
    89.                 slot0.State = "Saving to " + filename;
    90.             }
    91.             else {
    92.                 slot0.State = "Loading from " + filename;
    93.             }
    94.             //open the data.
    95.             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
    96.                                                                                              DataSource.ReadCacheOrNetwork,
    97.                                                                                              ConflictResolutionStrategy.UseLongestPlaytime,
    98.                                                                                              SavedGameOpened);
    99.         } else {
    100.             Debug.LogWarning("Error selecting save game: " + status);
    101.         }
    102.        
    103.     }
    104.    
    105.     public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
    106.         if(status == SavedGameRequestStatus.Success) {
    107.             if( mSaving) {
    108.                 slot0.State = "Opened, now writing";
    109.                 byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
    110.                 Debug.Log("Saving to " + game);
    111.                 byte[] data = slot0.ToBytes();
    112.                 TimeSpan playedTime = slot0.TotalPlayingTime;
    113.                 SavedGameMetadataUpdate.Builder builder =  new
    114.                     SavedGameMetadataUpdate.Builder()
    115.                         .WithUpdatedPlayedTime(playedTime)
    116.                         .WithUpdatedDescription("Saved Game at " + DateTime.Now);
    117.                
    118.                 if (pngData != null) {
    119.                     Debug.Log("Save image of len " + pngData.Length);
    120.                     builder = builder.WithUpdatedPngCoverImage(pngData);
    121.                 }
    122.                 else {
    123.                     Debug.Log ("No image avail");
    124.                 }
    125.                 SavedGameMetadataUpdate updatedMetadata  = builder.Build();
    126.                 ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
    127.             } else {
    128.                 slot0.State = "Opened, reading...";
    129.                 ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
    130.             }
    131.         } else {
    132.             Debug.LogWarning("Error opening game: " + status);
    133.         }
    134.     }
    135.    
    136.     public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
    137.         if (status == SavedGameRequestStatus.Success) {
    138.             Debug.Log("SaveGameLoaded, success=" + status);
    139.             slot0 = GameData.FromBytes(data);
    140.         } else {
    141.             Debug.LogWarning("Error reading game: " + status);
    142.         }
    143.     }
    144.    
    145.    
    146.     public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
    147.         if(status == SavedGameRequestStatus.Success) {
    148.             Debug.Log ("Game " + game.Description + " written");
    149.             slot0.State = "Saved!";
    150.         } else {
    151.             Debug.LogWarning("Error saving game: " + status);
    152.         }
    153.     }
    154.    
    155.    
    156.     public class GameData  {
    157.        
    158.         private TimeSpan mPlayingTime;
    159.         private DateTime mLoadedTime;
    160.         string mData;
    161.         string mState;
    162.        
    163.         static readonly string HEADER = "GDv1";
    164.        
    165.         public GameData(string data) {
    166.            
    167.             mData = data;
    168.             mState = "Initialized, modified";
    169.             mPlayingTime = new TimeSpan();
    170.             mLoadedTime = DateTime.Now;
    171.            
    172.         }
    173.        
    174.         public TimeSpan TotalPlayingTime {
    175.             get {
    176.                 TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
    177.                 return mPlayingTime.Add(delta);
    178.             }
    179.         }
    180.        
    181.         public override string ToString () {
    182.             string s = HEADER + ":" + mData;
    183.             s += ":" + TotalPlayingTime.TotalMilliseconds;
    184.             return s;
    185.         }
    186.        
    187.         public byte[] ToBytes() {
    188.             return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
    189.         }
    190.        
    191.        
    192.         public static GameData FromBytes (byte[] bytes) {
    193.             return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
    194.         }
    195.        
    196.         public static GameData FromString (string s) {
    197.             GameData gd = new GameData("initializing from string");
    198.             string[] p = s.Split(new char[] { ':' });
    199.             if (!p[0].StartsWith(HEADER)) {
    200.                 Debug.LogError("Failed to parse game data from: " + s);
    201.                 return gd;
    202.             }
    203.             gd.mData = p[1];
    204.             double val = Double.Parse(p[2]);
    205.             gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
    206.            
    207.             gd.mLoadedTime = DateTime.Now;
    208.             gd.mState = "Loaded successfully";
    209.             return gd;
    210.         }
    211.        
    212.         public string Data {
    213.             get {
    214.                 return mData;
    215.             }
    216.            
    217.             set {
    218.                 mData = value;
    219.                 mState += ", modified";
    220.             }
    221.            
    222.         }
    223.        
    224.         public string State {
    225.             get {
    226.                 return mState;
    227.             }
    228.            
    229.             set {
    230.                 mState = value;
    231.             }
    232.         }
    233.        
    234.     }
    With this I only save and load blank info, so nothing is saved, can anyone help me? I would like to know where I have to put the info that I want to be saved, for example, a float.

    Thanks!
     
  2. el_saq

    el_saq

    Joined:
    Feb 6, 2015
    Posts:
    7
    Anybody???
     
  3. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
    I've been struggling to get mine to work as well and there's NO examples online that are complete. The github page shows the code snippets but doesn't give the full picture. If I copy paste (and then modify to work for my game and actually compile) and change as little as possible it generates errors and doesn't really work. Looking for any one person to post a full working example is like pulling teeth.
     
  4. Chris-Trueman

    Chris-Trueman

    Joined:
    Oct 10, 2014
    Posts:
    1,256
    Google provides samples on github as well. I had saving/loading, leader boards and achievements up and running in a few hours, using those sample apps and a Google Play developer account.

    I used the Cubic Pilot 4.6 code mostly. Look at the GameManager and GameProgress classes. They contain the relevant code for what you want to do.
     
  5. ar61

    ar61

    Joined:
    Oct 10, 2012
    Posts:
    2
  6. WikiMalik

    WikiMalik

    Joined:
    Nov 13, 2014
    Posts:
    16
  7. jtsmith1287

    jtsmith1287

    Joined:
    Aug 3, 2014
    Posts:
    787
  8. scott31

    scott31

    Joined:
    May 7, 2017
    Posts:
    3
    This is why we need time travel...