Search Unity

Google Play Service and JSON

Discussion in 'Android' started by VREntertainment, Mar 15, 2019.

  1. VREntertainment

    VREntertainment

    Joined:
    Aug 22, 2015
    Posts:
    15
    Hi. I have small problem. Because In console I have debugs with "save" and "load", but via Alfa end Beta test by the google, the data is not savings. I have a few scripts. Meybe someone can help me ?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CloudVariables : MonoBehaviour {
    6.  
    7.     public static int gold { get; set; }
    8.     public static int diamonds { get; set; }
    9.      public static int currentHealth { get; set; }
    10.  
    11.     public static int[] ImportantValues { get; set; }
    12.  
    13.     private void Awake()
    14.     {
    15.         ImportantValues = new int[18] ;
    16.     }
    17.  
    18. }
    19.  
    Code (CSharp):
    1. using GooglePlayGames;
    2. using GooglePlayGames.BasicApi;
    3. using GooglePlayGames.BasicApi.SavedGame;
    4. using System.Text;
    5. using UnityEngine;
    6.  
    7. public class PlayGamesScript : MonoBehaviour
    8. {
    9.  
    10.     public static PlayGamesScript Instance { get; private set; }
    11.  
    12.     const string SAVE_NAME = "Pocket Dragon";
    13.     bool isSaving;
    14.     bool isCloudDataLoaded = false;
    15.  
    16.     // Use this for initialization
    17.     void Start()
    18.     {
    19.         Instance = this;
    20.         //setting default value, if the game is played for the first time
    21.         if (!PlayerPrefs.HasKey(SAVE_NAME))
    22.             PlayerPrefs.SetString(SAVE_NAME, string.Empty);
    23.         //tells us if it's the first time that this game has been launched after install - 0 = no, 1 = yes
    24.         if (!PlayerPrefs.HasKey("IsFirstTime"))
    25.             PlayerPrefs.SetInt("IsFirstTime", 1);
    26.  
    27.         LoadLocal(); //we want to load local data first because loading from cloud can take quite a while, if user progresses while using local data, it will all
    28.                      //sync in our comparating loop in StringToGameData(string, string)
    29.  
    30.         PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
    31.             .EnableSavedGames().Build();
    32.         PlayGamesPlatform.InitializeInstance(config);
    33.         PlayGamesPlatform.Activate();
    34.  
    35.         SignIn();
    36.     }
    37.  
    38.     void SignIn()
    39.     {
    40.         //when authentication process is done (successfuly or not), we load cloud data
    41.         Social.localUser.Authenticate(success => { LoadData(); });
    42.     }
    43.  
    44.     #region Saved Games
    45.     //making a string out of game data (highscores...)
    46.     string GameDataToString()
    47.     {
    48.         return JsonUtil.CollectionToJsonString(CloudVariables.ImportantValues, "myKey");
    49.     }
    50.  
    51.     //this overload is used when user is connected to the internet
    52.     //parsing string to game data (stored in CloudVariables), also deciding if we should use local or cloud save
    53.     void StringToGameData(string cloudData, string localData)
    54.     {
    55.         if (cloudData == string.Empty)
    56.         {
    57.             StringToGameData(localData);
    58.             isCloudDataLoaded = true;
    59.             return;
    60.         }
    61.         int[] cloudArray = JsonUtil.JsonStringToArray(cloudData, "myKey", str => int.Parse(str));
    62.  
    63.         if (localData == string.Empty)
    64.         {
    65.             CloudVariables.ImportantValues = cloudArray;
    66.             PlayerPrefs.SetString(SAVE_NAME, cloudData);
    67.             isCloudDataLoaded = true;
    68.             return;
    69.         }
    70.         int[] localArray = JsonUtil.JsonStringToArray(localData, "myKey", str => int.Parse(str));
    71.  
    72.         //if it's the first time that game has been launched after installing it and successfuly logging into Google Play Games
    73.         if (PlayerPrefs.GetInt("IsFirstTime") == 1)
    74.         {
    75.             Debug.Log("IsFirstTime");
    76.             //set playerpref to be 0 (false)
    77.             PlayerPrefs.SetInt("IsFirstTime", 0);
    78.             for (int i = 0; i < cloudArray.Length; i++)
    79.                 if (cloudArray[i] > localArray[i]) //cloud save is more up to date
    80.                 {
    81.                     //set local save to be equal to the cloud save
    82.                     PlayerPrefs.SetString(SAVE_NAME, cloudData);
    83.                 }
    84.            
    85.  
    86.         }
    87.         //if it's not the first time, start comparing
    88.         else
    89.         {
    90.             for (int i = 0; i < cloudArray.Length; i++)
    91.                 //comparing integers, if one int has higher score in it than the other, we update it
    92.                 if (localArray[i] > cloudArray[i])
    93.                 {
    94.                     Debug.Log("IsNotFirstTime");
    95.                     //update the cloud save, first set CloudVariables to be equal to localSave
    96.                     CloudVariables.ImportantValues = localArray;
    97.                     isCloudDataLoaded = true;
    98.                     //saving the updated CloudVariables to the cloud
    99.                     SaveData();
    100.                     return;
    101.                 }
    102.         }
    103.         //if the code above doesn't trigger return and the code below executes,
    104.         //cloud save and local save are identical, so we can load either one
    105.         CloudVariables.ImportantValues = cloudArray;
    106.         isCloudDataLoaded = true;
    107.     }
    108.  
    109.     //this overload is used when there's no internet connection - loading only local data
    110.     void StringToGameData(string localData)
    111.     {
    112.         if (localData != string.Empty)
    113.             CloudVariables.ImportantValues = JsonUtil.JsonStringToArray(localData, "myKey",
    114.                                                                         str => int.Parse(str));
    115.     }
    116.  
    117.     //used for loading data from the cloud or locally
    118.     public void LoadData()
    119.     {
    120.         Debug.Log("LoadData");
    121.         //basically if we're connected to the internet, do everything on the cloud
    122.         if (Social.localUser.authenticated)
    123.         {
    124.             isSaving = false;
    125.             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME,
    126.                 DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
    127.         }
    128.         //this will basically only run in Unity Editor, as on device,
    129.         //localUser will be authenticated even if he's not connected to the internet (if the player is using GPG)
    130.         else
    131.         {
    132.             LoadLocal();
    133.         }
    134.     }
    135.  
    136.     private void LoadLocal()
    137.     {
    138.         StringToGameData(PlayerPrefs.GetString(SAVE_NAME));
    139.         Debug.Log("LoadLocal");
    140.     }
    141.  
    142.     //used for saving data to the cloud or locally
    143.     public void SaveData()
    144.     {
    145.         //if we're still running on local data (cloud data has not been loaded yet), we also want to save only locally
    146.         if (!isCloudDataLoaded)
    147.         {
    148.             SaveLocal();
    149.             return;
    150.         }
    151.         //same as in LoadData
    152.         if (Social.localUser.authenticated)
    153.         {
    154.             isSaving = true;
    155.             ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithManualConflictResolution(SAVE_NAME,
    156.                 DataSource.ReadCacheOrNetwork, true, ResolveConflict, OnSavedGameOpened);
    157.         }
    158.         else
    159.         {
    160.             SaveLocal();
    161.         }
    162.     }
    163.  
    164.     private void SaveLocal()
    165.     {
    166.         Debug.Log("SaveLocal");
    167.         PlayerPrefs.SetString(SAVE_NAME, GameDataToString());
    168.     }
    169.  
    170.     private void ResolveConflict(IConflictResolver resolver, ISavedGameMetadata original, byte[] originalData,
    171.         ISavedGameMetadata unmerged, byte[] unmergedData)
    172.     {
    173.         if (originalData == null)
    174.             resolver.ChooseMetadata(unmerged);
    175.         else if (unmergedData == null)
    176.             resolver.ChooseMetadata(original);
    177.         else
    178.         {
    179.             //decoding byte data into string
    180.             string originalStr = Encoding.ASCII.GetString(originalData);
    181.             string unmergedStr = Encoding.ASCII.GetString(unmergedData);
    182.  
    183.             //parsing
    184.             int[] originalArray = JsonUtil.JsonStringToArray(originalStr, "myKey", str => int.Parse(str));
    185.             int[] unmergedArray = JsonUtil.JsonStringToArray(unmergedStr, "myKey", str => int.Parse(str));
    186.  
    187.             for (int i = 0; i < originalArray.Length; i++)
    188.             {
    189.                 //if original score is greater than unmerged
    190.                 if (originalArray[i] > unmergedArray[i])
    191.                 {
    192.                     resolver.ChooseMetadata(original);
    193.                     return;
    194.                 }
    195.                 //else (unmerged score is greater than original)
    196.                 else if (unmergedArray[i] > originalArray[i])
    197.                 {
    198.                     resolver.ChooseMetadata(unmerged);
    199.                     return;
    200.                 }
    201.             }
    202.             //if return doesn't get called, original and unmerged are identical
    203.             //we can keep either one
    204.             resolver.ChooseMetadata(original);
    205.         }
    206.     }
    207.  
    208.     private void OnSavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game)
    209.     {
    210.         //if we are connected to the internet
    211.         if (status == SavedGameRequestStatus.Success)
    212.         {
    213.             //if we're LOADING game data
    214.             if (!isSaving)
    215.                 LoadGame(game);
    216.             //if we're SAVING game data
    217.             else
    218.                 SaveGame(game);
    219.         }
    220.         //if we couldn't successfully connect to the cloud, runs while on device,
    221.         //the same code that is in else statements in LoadData() and SaveData()
    222.         else
    223.         {
    224.             if (!isSaving)
    225.                 LoadLocal();
    226.             else
    227.                 SaveLocal();
    228.         }
    229.     }
    230.  
    231.     private void LoadGame(ISavedGameMetadata game)
    232.     {
    233.         Debug.Log("LoadGame2");
    234.         ((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game, OnSavedGameDataRead);
    235.     }
    236.  
    237.     private void SaveGame(ISavedGameMetadata game)
    238.     {
    239.         Debug.Log("SaveGame2");
    240.         string stringToSave = GameDataToString();
    241.         //saving also locally (can also call SaveLocal() instead)
    242.         PlayerPrefs.SetString(SAVE_NAME, stringToSave);
    243.  
    244.         //encoding to byte array
    245.         byte[] dataToSave = Encoding.ASCII.GetBytes(stringToSave);
    246.         //updating metadata with new description
    247.         SavedGameMetadataUpdate update = new SavedGameMetadataUpdate.Builder().Build();
    248.         //uploading data to the cloud
    249.         ((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game, update, dataToSave,
    250.             OnSavedGameDataWritten);
    251.     }
    252.  
    253.     //callback for ReadBinaryData
    254.     private void OnSavedGameDataRead(SavedGameRequestStatus status, byte[] savedData)
    255.     {
    256.         //if reading of the data was successful
    257.         if (status == SavedGameRequestStatus.Success)
    258.         {
    259.             string cloudDataString;
    260.             //if we've never played the game before, savedData will have length of 0
    261.             if (savedData.Length == 0)
    262.                 //in such case, we want to assign default value to our string
    263.                 cloudDataString = string.Empty;
    264.             //otherwise take the byte[] of data and encode it to string
    265.             else
    266.                 cloudDataString = Encoding.ASCII.GetString(savedData);
    267.  
    268.             //getting local data (if we've never played before on this device, localData is already
    269.             //string.Empty, so there's no need for checking as with cloudDataString)
    270.             string localDataString = PlayerPrefs.GetString(SAVE_NAME);
    271.  
    272.             //this method will compare cloud and local data
    273.             StringToGameData(cloudDataString, localDataString);
    274.         }
    275.     }
    276.  
    277.     //callback for CommitUpdate
    278.     private void OnSavedGameDataWritten(SavedGameRequestStatus status, ISavedGameMetadata game)
    279.     {
    280.  
    281.     }
    282.     #endregion /Saved Games
    283. }
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3.  
    4. public class UIScript : MonoBehaviour
    5. {
    6.     public Text[] ValueTextArray;
    7.  
    8.     public void UpdateAll()
    9.     {
    10.         for (int i = 0; i < CloudVariables.ImportantValues.Length; i++)
    11.             ValueTextArray[i].text = CloudVariables.ImportantValues[i].ToString();
    12.     }
    13.  
    14.     public void Save()
    15.     {
    16.         PlayGamesScript.Instance.SaveData();
    17.     }
    18.  
    19.     public void Increment(int index)
    20.     {
    21.         CloudVariables.ImportantValues[index]++;
    22.         ValueTextArray[index].text = CloudVariables.ImportantValues[index].ToString();
    23.     }
    24. }
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class DiamondsManager : MonoBehaviour
    6. {
    7.     public static int diamonds;        // The player's score.
    8.  
    9.  
    10.     Text text;                      // Reference to the Text component.
    11.  
    12.  
    13.     void Start ()
    14.     {
    15.         // Set up the reference.
    16.         text = GetComponent<Text>();
    17.         PlayGamesScript.Instance.LoadData();
    18.         // Reset the score.
    19.  
    20.     }
    21.  
    22.  
    23.     void Update()
    24.     {
    25.         // Set the displayed text to be the word "Score" followed by the score value.
    26.         text.text = "" + diamonds;
    27.         PlayGamesScript.Instance.SaveData();
    28.     }
    29. }
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class GoldManager : MonoBehaviour
    6. {
    7.     public static int gold;        // The player's score.
    8.  
    9.  
    10.     Text text;                      // Reference to the Text component.
    11.  
    12.  
    13.     void Start()
    14.     {
    15.      
    16.         text = GetComponent<Text>();
    17.         PlayGamesScript.Instance.LoadData();
    18.     }
    19.  
    20.  
    21.     void Update()
    22.     {
    23.         PlayGamesScript.Instance.SaveData();
    24.         // Set the displayed text to be the word "Score" followed by the score value.
    25.         text.text = "" + gold;
    26.         PlayGamesScript.Instance.SaveData();
    27.  
    28.     }
    29. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class BrushShop : MonoBehaviour {
    6.     public GameObject firstActiveGameObject;
    7.     private DinoHealthScript dinoHealthScript;
    8.     public Animator anim;
    9.     // Use this for initialization
    10.     void Start()
    11.     {
    12.  
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         for (int i = 0; i < gameObject.transform.childCount; i++)
    19.         {
    20.             if (gameObject.transform.GetChild(i).gameObject.activeSelf == true)
    21.             {
    22.                 firstActiveGameObject = gameObject.transform.GetChild(i).gameObject;
    23.                 dinoHealthScript = firstActiveGameObject.GetComponent<DinoHealthScript>();
    24.             }
    25.         }
    26.         GameObject animal = null;
    27.         animal = GameObject.FindWithTag("animal");
    28.         anim = animal.GetComponent<Animator>();
    29.     }
    30.     IEnumerator Wait()
    31.     {
    32.         yield return new WaitForSeconds(3);
    33.         anim.SetBool("Clean", false);
    34.     }
    35.  
    36.     public void BuyShower()
    37.     {
    38.         if (GoldManager.gold >= 50)
    39.         {
    40.             GoldManager.gold -= 50;
    41.             DinoHealthScript.Instance.currentHealth += 200;
    42.             PlayGamesScript.Instana6ce.SaveData();
    43.             anim.SetBool("Clean", true);
    44.             StartCoroutine(Wait());
    45.         }
    46.     }
    47.     public void BuyToilet()
    48.     {
    49.         if (GoldManager.gold >= 80)
    50.         {
    51.             GoldManager.gold -= 80;
    52.             DinoHealthScript.Instance.currentHealth += 400;
    53.             PlayGamesScript.Instance.SaveData();
    54.             anim.SetBool("Clean", true);
    55.             StartCoroutine(Wait());
    56.         }
    57.     }
    58.     public void BuyBrush()
    59.     {
    60.         if (GoldManager.gold >= 140)
    61.         {
    62.             GoldManager.gold -= 140;
    63.             DinoHealthScript.Instance.currentHealth += 800;
    64.             PlayGamesScript.Instance.SaveData();
    65.             anim.SetBool("Clean", true);
    66.             StartCoroutine(Wait());
    67.         }
    68.     }
    69.     public void BuyToothbrush()
    70.     {
    71.         if (GoldManager.gold >= 200)
    72.         {
    73.             GoldManager.gold -= 200;
    74.             DinoHealthScript.Instance.currentHealth += 1600;
    75.             PlayGamesScript.Instance.SaveData();
    76.             anim.SetBool("Clean", true);
    77.             StartCoroutine(Wait());
    78.         }
    79.     }
    80. }
    81.  

    I know, it`s a lot of code.. But if someone see mistake, please help !