Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
0
Question by Hoffa25 · Jan 02, 2015 at 11:06 AM · plugingoogle

How to convert match data to byte?

Hi

Im a beginner trying to make a turn based game using the google game services unity plugin, https://github.com/playgameservices/play-games-plugin-for-unity/blob/master/TBMP.md. I have come over some sample codes and put them in my game and everything is actually working fine (to my surprice). However, ofcourse, the sample games doesnt convert the same kind of data as I want to do in my game. My specific game data consists of ints and bools and from what I can see my code only converts strings.. right? So my question is: How do I modify the code so it will work with my game data? I want to be able to convert and "deconvert". Im actually not sure about all thats going on in this script... but I think the convertion and deconvertion happens on lines 110-240.

 public class SaveSample : MonoBehaviour {
     
     
     System.Action<bool> mAuthCallback;
     
     GameData slot0;
     
     bool mSaving;
     private Texture2D mScreenImage;
     
     // Use this 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. This will make it the default
         // implementation of Social.Active
         PlayGamesPlatform.Activate();
         
         // enable debug logs (note: we do this because this is a sample; on your production
         // app, you probably don't want this turned on by default, as it will fill the user's
         // logs with debug info).
         PlayGamesPlatform.DebugLogEnabled = true;
         
         //Login explicitly for this sample, usually this 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();
     }
     
     protected virtual void OnGUI() {
         
         Screen.fullScreen = true;
         
         int buttonHeight = Screen.height / 20;
         int buttonWidth = Screen.width / 5;
         
         GUI.skin.label.fontSize = 60;
         GUI.skin.button.fontSize = 60;
         
         
         Rect statusRect = new Rect(10,20,Screen.width,200);
         Rect dataRect  = new Rect( 10, 250, Screen.width,100);
         
         Rect b1Rect = new Rect(10, 800, buttonWidth, buttonHeight);
         Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth, b1Rect.y, buttonWidth, buttonHeight);
         
         if(!Social.localUser.authenticated) {
             if(GUI.Button(b1Rect, "Signin")) {
                 Social.localUser.Authenticate(mAuthCallback);
             }
         }
         else {
             if(GUI.Button(b1Rect, "Load")) {
                 mSaving = false;
                 ((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
                                                                                    4,false,false,SavedGameSelected);
             }
             
             GUI.Label(dataRect, slot0.Data);
         }
         
         if(GUI.Button(b2Rect, "Save")) {
             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);
         }
         
         GUI.Label(statusRect, slot0.State);
         
     }
     
     
     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;
             }
         }
         
     }
 }
Comment
Add comment
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

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.

Follow this Question

Answers Answers and Comments

2 People are following this question.

avatar image avatar image

Related Questions

GoogleVR on Unity has error can't load libaudioplugingvrunity 0 Answers

GPGS Reporting score/progress doesn't work 0 Answers

Google Play Services, how to track wins and losses? 0 Answers

Android Amazon or Google plugin 1 Answer

Where to get official support for the Google Play OBB Downloader plugin? 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