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 /
  • Help Room /
avatar image
0
Question by unity_5hp234hp · Dec 28, 2020 at 06:11 AM · unity 2dsavesave datacloudsaveload

Problem With Unity Cloud Save (Google Play Services)

If I run game, Counter of total games played good works, but Counter of money becomes such as TotalGamesCouneter. Please check my code and explain why it not work correctly. I'm noob in programming on c#, so this code written by me may not be optimized or strange. If you are able, please write a simple code that can replace mine. The idea of the code is that with each change of coins or games, it is changed and stored on the cloud, and when the user comes in again, all the data is loaded from the cloud. If you see comment AD This in the code it means that I added a save for total played games.



PlayGamesScript.cs

 using GooglePlayGames;
 using GooglePlayGames.BasicApi;
 using GooglePlayGames.BasicApi.SavedGame;
 using System.Text;
 using UnityEngine;
  
 public class PlayGamesScript : MonoBehaviour{
  
     public static PlayGamesScript Instance { get; private set; }
  
     const string SAVE_NAME = "Tutorial";
     bool isSaving;
     bool isCloudDataLoaded = false;
  
     void Start()
     {
         Instance = this;
         if (!PlayerPrefs.HasKey(SAVE_NAME))
             PlayerPrefs.SetString(SAVE_NAME, "0");
         if (!PlayerPrefs.HasKey("IsFirstTime"))
             PlayerPrefs.SetInt("IsFirstTime", 1);
  
         LoadLocal();
 
         PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().EnableSavedGames().Build();
         PlayGamesPlatform.InitializeInstance(config);
         PlayGamesPlatform.Activate();
 
         SignIn();
     }
  
     void SignIn(){
         Social.localUser.Authenticate(success => { LoadData(); });
     }
  
     #region Saved Games
     string GameDataToString(){
         return CloudVariables.Highscore.ToString();
     }
     string TotalGamesToString(){
         return CloudVariables.Games.ToString(); // AD This
     }
 
     void StringToGameData(string cloudData, string localData){
         if (PlayerPrefs.GetInt("IsFirstTime") == 1){
             PlayerPrefs.SetInt("IsFirstTime", 0);
             if (int.Parse(cloudData) > int.Parse(localData)){
                 PlayerPrefs.SetString(SAVE_NAME, cloudData);
             }
         }else{
             if (int.Parse(localData) > int.Parse(cloudData)){
                 CloudVariables.Highscore = int.Parse(localData);
                 CloudVariables.Games = int.Parse(localData); // AD This
                 AddScoreToLeaderboard(GPGSIds.leaderboard_leaderboard, CloudVariables.Highscore);
                 isCloudDataLoaded = true;
                 SaveData();
                 return;
             }
         }
         CloudVariables.Highscore = int.Parse(cloudData);
         CloudVariables.Games = int.Parse(cloudData); // AD This
         isCloudDataLoaded = true;
     }
  
     void StringToGameData(string localData){
         CloudVariables.Highscore = int.Parse(localData);
         CloudVariables.Games = int.Parse(localData); // AD This
     }
  
     public void LoadData(){
         if (Social.localUser.authenticated){
             isSaving = false;
             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME,
                 DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
         }else{
             LoadLocal();
         }
     }
  
     private void LoadLocal(){
         StringToGameData(PlayerPrefs.GetString(SAVE_NAME));
     }
  
     public void SaveData(){
         if (!isCloudDataLoaded){
             SaveLocal();
             return;
         }
         if (Social.localUser.authenticated){
             isSaving = true;
             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME,
                 DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
         }else{
             SaveLocal();
         }
     }
  
     private void SaveLocal(){
         PlayerPrefs.SetString(SAVE_NAME, GameDataToString());
         PlayerPrefs.SetString(SAVE_NAME, TotalGamesToString()); // AD This
     }
  
     private void ResolveConflict(IConflictResolver resolver, ISavedGameMetadata original, byte[] originalData,
         ISavedGameMetadata unmerged, byte[] unmergedData){
         if (originalData == null)
             resolver.ChooseMetadata(unmerged);
         else if (unmergedData == null)
             resolver.ChooseMetadata(original);
         else{
             string originalStr = Encoding.ASCII.GetString(originalData);
             string unmergedStr = Encoding.ASCII.GetString(unmergedData);
             
             int originalNum = int.Parse(originalStr);
             int unmergedNum = int.Parse(unmergedStr);
  
             if (originalNum > unmergedNum){
                 resolver.ChooseMetadata(original);
                 return;
             }
             else if (unmergedNum > originalNum){
                 resolver.ChooseMetadata(unmerged);
                 return;
             }
             resolver.ChooseMetadata(original);
         }
     }
  
     private void OnSavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game){
         if (status == SavedGameRequestStatus.Success){
             if (!isSaving)
                 LoadGame(game);
             else
                 SaveGame(game);
         }else{
             if (!isSaving)
                 LoadLocal();
             else
                 SaveLocal();
         }
     }
  
     private void LoadGame(ISavedGameMetadata game){
         ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game, OnSavedGameDataRead);
     }
  
     private void SaveGame(ISavedGameMetadata game){
         string stringToSave = GameDataToString();
         string stringToSaveGames = TotalGamesToString(); // AD This
         PlayerPrefs.SetString(SAVE_NAME, stringToSave);
         PlayerPrefs.SetString(SAVE_NAME, stringToSaveGames); // AD This
  
         byte[] dataToSave = Encoding.ASCII.GetBytes(stringToSave);
         byte[] dataToSaveGames = Encoding.ASCII.GetBytes(stringToSaveGames); // AD This
         SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
         ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game, update, dataToSave, // AD This
             OnSavedGameDataWritten);
     }
  
     private void OnSavedGameDataRead(SavedGameRequestStatus status, byte[] savedData){
         if (status == SavedGameRequestStatus.Success){
             string cloudDataString;
             if (savedData.Length == 0)
                 cloudDataString = "0";
             else
                 cloudDataString =  Encoding.ASCII.GetString(savedData);
             
             string localDataString = PlayerPrefs.GetString(SAVE_NAME);
             
             StringToGameData(cloudDataString, localDataString);
         }
     }
     private void OnSavedGameDataWritten(SavedGameRequestStatus status, ISavedGameMetadata game){
  
     }
     #endregion /Saved Games
  
     #region Achievements
  
     public static void IncrementAchievement(string id, int stepsToIncrement){
         PlayGamesPlatform.Instance.IncrementAchievement(id, stepsToIncrement, success => { });
     }
     #endregion /Achievements
  
     #region Leaderboards
     public static void AddScoreToLeaderboard(string leaderboardId, long score){
         Social.ReportScore(score, leaderboardId, success => { });
     }
     #endregion /Leaderboards
  
 }





ManagerScript.cs

 using UnityEngine;
  
 public class ManagerScript : MonoBehaviour {
     public static ManagerScript Instance { get; private set; }
     public static int Counter { get; private set; }
     public static int CounterGames { get; private set; } // AD This
  
     void Start () {
         Instance = this;
         UIScript.Instance.UpdateHighscoreText();
         UIScript.Instance.UpdateGamesText(); // AD This
     }
  
     public void IncrementCounter(){
         Counter=30;
         UIScript.Instance.UpdatePointsText();
         Instance.RestartGame();
     }
     public void IncrementGamesCounter(){
         CounterGames++;
         UIScript.Instance.UpdateGamesPointsText(); // AD This
         Instance.RestartGame();
     }
  
     public void RestartGame(){
         PlayGamesScript.AddScoreToLeaderboard(GPGSIds.leaderboard_leaderboard, Counter);
  
         CloudVariables.Highscore += Counter;
         CloudVariables.Games += CounterGames; // AD This
         PlayGamesScript.Instance.SaveData();
         Counter=0;
         CounterGames=0; // AD This
         UIScript.Instance.UpdatePointsText();
         UIScript.Instance.UpdateGamesText(); // AD This
         UIScript.Instance.UpdateGamesPointsText(); // AD This
         UIScript.Instance.UpdateHighscoreText();
     }
  
 }





CloudVariables.cs

 using UnityEngine;
  
 public class CloudVariables : MonoBehaviour {
     public static int Highscore { get; set; }
     public static int Games { get; set; } // AD This
 }





UIScript.cs

 using UnityEngine;
 using UnityEngine.UI;
  
 public class UIScript : MonoBehaviour {
     public static UIScript Instance { get; private set; }
 
     [SerializeField]
     private Text pointsTxt;
     [SerializeField]
     private Text highscoreTxt;
     [SerializeField]
     private Text pointsGamesTxt; // AD This
     [SerializeField]
     private Text gamesTxt; // AD This
 
     void Start () {
         Instance = this;
         pointsTxt.text = ManagerScript.Counter.ToString();
         pointsGamesTxt.text = ManagerScript.CounterGames.ToString(); // AD This
         highscoreTxt.text = CloudVariables.Highscore.ToString();
         gamesTxt.text = CloudVariables.Games.ToString(); // AD This
     }
 
     public void GetPoint(){
         ManagerScript.Instance.IncrementCounter();
     }
     public void GetGame(){
         ManagerScript.Instance.IncrementGamesCounter(); // AD This
     }
     public void UpdatePointsText(){
         pointsTxt.text = ManagerScript.Counter.ToString();
     }
     public void UpdateHighscoreText(){
         highscoreTxt.text = CloudVariables.Highscore.ToString();
     }
     public void UpdateGamesPointsText(){
         pointsGamesTxt.text = ManagerScript.CounterGames.ToString();
     }
     public void UpdateGamesText(){
         gamesTxt.text = CloudVariables.Games.ToString(); // AD This
     }
 }


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

163 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can I save my options menu? 0 Answers

problem with loading data with serialization in the right time 0 Answers

Save location of created UI elements to JSON so it can load later 0 Answers

how to save a lot of character data? 1 Answer

Bug Wtih Unity Cloud Save (Google Play Services) 0 Answers


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