• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by el_saq · Feb 13, 2015 at 06:55 AM · scripting problempluginpluginsgoogle play gamesandroidplugin

Google Play Services Plugin Save/Load

I´m using official plugin:

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

I have t$$anonymous$$s code for saving and loading:

     System.Action<bool> mAuthCallback;
     
     GameData slot0;
     
     bool mSaving;
     private Texture2D mScreenImage;
     
     // Use t$$anonymous$$s for initialization
     void Start () {
         
         slot0 = new GameData("New game");
         mAuthCallback = (bool success) => {
             
             if (success) {
                 Debug.Log("Authentication was successful!");
                 slot0.State = "Click load or save";
             }
             else {
                 Debug.LogWarning("Authentication failed!");
             }
             
         };
         
         
         PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
             .EnableSavedGames()
                 .Build();
         PlayGamesPlatform.InitializeInstance(config);
         
         // Activate the Play Games platform. T$$anonymous$$s will make it the default
         // implementation of Social.Active
         PlayGamesPlatform.Activate();
         
         // enable debug logs (note: we do t$$anonymous$$s because t$$anonymous$$s is a sample; on your production
         // app, you probably don't want t$$anonymous$$s turned on by default, as it will fill the user's
         // logs with debug info).
         PlayGamesPlatform.DebugLogEnabled = true;
         
         //Login explicitly for t$$anonymous$$s sample, usually t$$anonymous$$s would be silent
         PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
         
         
     }
     
     public void CaptureScreenshot() {
         mScreenImage = new Texture2D(Screen.width, Screen.height);
         mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
         mScreenImage.Apply();
     }
 
     // Save Button
 
     public void SaveButton () 
     {
         int idx = slot0.Data.IndexOf("_");
         if (idx > 0) {
             int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
             val++;
             slot0.Data = "Save_" + val;
         }
         else {
             slot0.Data = "Save_0";
         }
         mSaving = true;
         CaptureScreenshot();
         ((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
                                                                            4,true,true,SavedGameSelected);
     }
 
     // Load Button
 
     public void LoadButton () 
     {
         mSaving = false;
         ((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
                                                                            4,false,false,SavedGameSelected);
     }
     
     
     public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
         
         if (status == SelectUIStatus.SavedGameSelected) {
             string filename = game.Filename;
             Debug.Log("opening saved game:  " + game);
             if(mSaving && (filename == null || filename.Length == 0)) {
                 filename = "save" + DateTime.Now.ToBinary();
             }
             if (mSaving) {
                 slot0.State = "Saving to " + filename;
             }
             else {
                 slot0.State = "Loading from " + filename;
             }
             //open the data.
             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
                                                                                              DataSource.ReadCacheOrNetwork,
                                                                                              ConflictResolutionStrategy.UseLongestPlaytime,
                                                                                              SavedGameOpened);
         } else {
             Debug.LogWarning("Error selecting save game: " + status);
         }
         
     }
     
     public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
         if(status == SavedGameRequestStatus.Success) {
             if( mSaving) {
                 slot0.State = "Opened, now writing";
                 byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
                 Debug.Log("Saving to " + game);
                 byte[] data = slot0.ToBytes();
                 TimeSpan playedTime = slot0.TotalPlayingTime;
                 SavedGameMetadataUpdate.Builder builder =  new 
                     SavedGameMetadataUpdate.Builder()
                         .WithUpdatedPlayedTime(playedTime)
                         .WithUpdatedDescription("Saved Game at " + DateTime.Now);
                 
                 if (pngData != null) {
                     Debug.Log("Save image of len " + pngData.Length);
                     builder = builder.WithUpdatedPngCoverImage(pngData);
                 }
                 else {
                     Debug.Log ("No image avail");
                 }
                 SavedGameMetadataUpdate updatedMetadata  = builder.Build();
                 ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
             } else {
                 slot0.State = "Opened, reading...";
                 ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
             }
         } else {
             Debug.LogWarning("Error opening game: " + status);
         }
     }
     
     public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
         if (status == SavedGameRequestStatus.Success) {
             Debug.Log("SaveGameLoaded, success=" + status);
             slot0 = GameData.FromBytes(data);
         } else {
             Debug.LogWarning("Error reading game: " + status);
         }
     }
     
     
     public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
         if(status == SavedGameRequestStatus.Success) {
             Debug.Log ("Game " + game.Description + " written");
             slot0.State = "Saved!";
         } else {
             Debug.LogWarning("Error saving game: " + status);
         }
     }
     
     
     public class GameData  {
         
         private TimeSpan mPlayingTime;
         private DateTime mLoadedTime;
         string mData;
         string mState;
         
         static readonly string HEADER = "GDv1";
         
         public GameData(string data) {
             
             mData = data;
             mState = "Initialized, modified";
             mPlayingTime = new TimeSpan();
             mLoadedTime = DateTime.Now;
             
         }
         
         public TimeSpan TotalPlayingTime {
             get {
                 TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
                 return mPlayingTime.Add(delta);
             }
         }
         
         public override string ToString () {
             string s = HEADER + ":" + mData;
             s += ":" + TotalPlayingTime.TotalMilliseconds;
             return s;
         }
         
         public byte[] ToBytes() {
             return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
         }
         
         
         public static GameData FromBytes (byte[] bytes) {
             return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
         }
         
         public static GameData FromString (string s) {
             GameData gd = new GameData("initializing from string");
             string[] p = s.Split(new char[] { ':' });
             if (!p[0].StartsWith(HEADER)) {
                 Debug.LogError("Failed to parse game data from: " + s);
                 return gd;
             }
             gd.mData = p[1];
             double val = Double.Parse(p[2]);
             gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
             
             gd.mLoadedTime = DateTime.Now;
             gd.mState = "Loaded successfully";
             return gd;
         }
         
         public string Data {
             get {
                 return mData;
             }
             
             set {
                 mData = value;
                 mState += ", modified";
             }
             
         }
         
         public string State {
             get {
                 return mState;
             }
             
             set {
                 mState = value;
             }
         }
         
     }

With t$$anonymous$$s I only save and load blank info, so not$$anonymous$$ng 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!

Comment
alihamie

People who like this

1 Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Wicaodian · Jul 22, 2016 at 05:39 AM 0
Share

I am having issue with TimeSpan it says the name "TimeSpan" does not exist in this context. please help

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

GooglePlayGames plugin path not correct? 0 Answers

android time cheat plugin problem with broadcastreceiver 1 Answer

Web plugin like uWebKit for Android? 0 Answers

Plugins collide on Unity 5 0 Answers

Android plugin dependency 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges