Search Unity

My Save (PlayerPrefs) Dosen't Work On Android But works On pc build

Discussion in 'Scripting' started by unity_MPhbdR7wb7LlCQ, Feb 13, 2021.

  1. unity_MPhbdR7wb7LlCQ

    unity_MPhbdR7wb7LlCQ

    Joined:
    Sep 14, 2019
    Posts:
    15
    First Code :

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Xml;
    4. using UnityEngine.UI;
    5. using System;
    6.  
    7. namespace BusinessTycoonSim
    8. {
    9.    
    10.     public class LoadGameData : MonoBehaviour
    11.     {
    12.  
    13.  
    14.      
    15.         const string CurrencyDataFile = "BigNumbers";
    16.         const string resourcepath = "/FirstClassGameStudios/Resources/";
    17.  
    18.        
    19.         public delegate void LoadDataComplete();
    20.         public static event LoadDataComplete OnLoadDataComplete;
    21.  
    22.        
    23.         private TextAsset gameData;
    24.  
    25.  
    26.  
    27.  
    28.  
    29.         private GameObject storePanel;
    30.  
    31.  
    32.         private GameObject upgradePanel;
    33.  
    34.  
    35.  
    36.         private int upgradeCount;
    37.  
    38.  
    39.         private UIManager uiManagerObj;
    40.  
    41.         public string GameDataFile;
    42.  
    43.         #region Setters & Getters
    44.         public TextAsset GameData
    45.         {
    46.             get
    47.             {
    48.                 return gameData;
    49.             }
    50.  
    51.             set
    52.             {
    53.                 gameData = value;
    54.             }
    55.         }
    56.         public GameObject StorePanel
    57.         {
    58.             get
    59.             {
    60.                 return storePanel;
    61.             }
    62.  
    63.             set
    64.             {
    65.                 storePanel = value;
    66.             }
    67.         }
    68.         public int UpgradeCount
    69.         {
    70.             get
    71.             {
    72.                 return upgradeCount;
    73.             }
    74.  
    75.             set
    76.             {
    77.                 upgradeCount = value;
    78.             }
    79.         }
    80.         public UIManager UIManagerObj
    81.         {
    82.             get
    83.             {
    84.                 return uiManagerObj;
    85.             }
    86.  
    87.             set
    88.             {
    89.                 uiManagerObj = value;
    90.             }
    91.         }
    92.  
    93.         public GameObject UpgradePanel
    94.         {
    95.             get
    96.             {
    97.                 return upgradePanel;
    98.             }
    99.  
    100.             set
    101.             {
    102.                 upgradePanel = value;
    103.             }
    104.         }
    105.  
    106.         #endregion
    107.  
    108.         public void Start()
    109.         {
    110.            
    111.             gamemanager.CurrentState = gamemanager.State.Loading;
    112.  
    113.             storePanel = GameObject.Find("StorePanel");
    114.  
    115.             UpgradePanel = (GameObject)utils.FindInactiveObjects("UpgradesListPanel", typeof(GameObject));
    116.  
    117.  
    118.          
    119.  
    120.             if (storePanel == null || UpgradePanel == null)
    121.             {
    122.                 Debug.LogError("Could not find critical references to load game data: storePanel=" + storePanel.ToString() + ", UpgradePanel=" + UpgradePanel.ToString());
    123.  
    124.             }
    125.  
    126.            
    127.             LoadGameDataFromXML();
    128.         }
    129.  
    130.         public void LoadGameDataFromXML()
    131.         {
    132.  
    133.          
    134.             string Filepath = Application.dataPath + resourcepath + GameDataFile;
    135.             Debug.Log(Filepath);
    136.             GameData = Resources.Load("GameData/" + GameDataFile) as TextAsset;
    137.  
    138.             Debug.Log(GameData);
    139.  
    140.             /
    141.             LoadCurrencyData();
    142.  
    143.            
    144.             XmlDocument xmlDoc = new XmlDocument();
    145.             xmlDoc.LoadXml(GameData.text);
    146.  
    147.             // Load Game Manager Data
    148.             LoadGameManagerData(xmlDoc);
    149.  
    150.             // Load the Stores
    151.             LoadStores(xmlDoc);
    152.  
    153.            
    154.             DynamicScrollFitter(upgradePanel, upgradeCount, 1);
    155.             DynamicScrollFitter(storePanel, gamemanager.StoreList.Count, 2);
    156.  
    157.             if (OnLoadDataComplete != null) // Make sure we have at least one observer
    158.                 OnLoadDataComplete();
    159.             //new LoadPlayerDataPrefs().LoadSavedGame();
    160.  
    161.         }
    162.  
    163.  
    164.         public void LoadGameManagerData(XmlDocument xmlDoc)
    165.         {
    166.             // Load data items used within the gamemanager
    167.             gamemanager.StartingBalance = double.Parse(utils.LoadGameDataElement("StartingBalance", xmlDoc));
    168.             gamemanager.CompanyName = utils.LoadGameDataElement("CompanyName", xmlDoc);
    169.             gamemanager.GameName = utils.LoadGameDataElement("GameName", xmlDoc);
    170.             gamemanager.FirstStoreCount = utils.LoadGameDataElementInt("FirstStoreCount", xmlDoc);
    171.             gamemanager.ShareholderMultiplier = utils.LoadGameDataElementFloat("ShareHolderBonusPercent", xmlDoc);
    172.  
    173.  
    174.  
    175.         }
    176.      
    177.         void LoadStores(XmlDocument xmlDoc)
    178.         {
    179.             XmlNodeList StoreList = xmlDoc.GetElementsByTagName("store");
    180.  
    181.             // loop through all the store notes
    182.             foreach (XmlNode StoreInfo in StoreList)
    183.             {
    184.                 //Load Store Nodes for each store
    185.                 LoadStoreNodes(StoreInfo);
    186.  
    187.  
    188.             }
    189.  
    190.         }
    191.  
    192.      
    193.         void DynamicScrollFitter(GameObject Panel, int NumberOfItems, int NumCols)
    194.         {
    195.  
    196.             GridLayoutGroup layoutGroup = Panel.GetComponent<GridLayoutGroup>();
    197.             RectTransform myTransform = Panel.GetComponent<RectTransform>();
    198.  
    199.            
    200.             Vector2 cellSize = layoutGroup.cellSize;
    201.             RectOffset padding = layoutGroup.padding;
    202.  
    203.            
    204.             Vector2 newScale = myTransform.sizeDelta;
    205.  
    206.            
    207.             newScale.y = ((cellSize.y + layoutGroup.spacing.y) * NumberOfItems / NumCols);
    208.             newScale.y = newScale.y + padding.bottom;
    209.            
    210.             myTransform.sizeDelta = newScale;
    211.  
    212.  
    213.         }
    214.  
    215.        
    216.         void LoadStoreNodes(XmlNode StoreInfo)
    217.         {
    218.  
    219.             GameObject NewStore = (GameObject)Instantiate(Resources.Load("Prefabs/StorePrefab"));
    220.             store storeobj = NewStore.GetComponent<store>();
    221.  
    222.  
    223.             XmlNodeList StoreNodes = StoreInfo.ChildNodes;
    224.             foreach (XmlNode StoreNode in StoreNodes)
    225.             {
    226.  
    227.                 SetStoreObj(storeobj, StoreNode, NewStore);
    228.  
    229.             }
    230.  
    231.             // Connect our store to the parent panel
    232.             NewStore.transform.SetParent(StorePanel.transform);
    233.  
    234.  
    235.  
    236.          
    237.             gamemanager.AddStore(storeobj);
    238.         }
    239.  
    240.         // Check each node name and store the value in the appropriate property of the store node
    241.         void SetStoreObj(store storeobj, XmlNode StoreNode, GameObject NewStore)
    242.         {
    243.             // This will match the XML node 'name' for the store
    244.             if (StoreNode.Name == "name")
    245.             {
    246.                
    247.                 Text StoreText = NewStore.transform.Find("StoreNameText").GetComponent<Text>();
    248.                
    249.                 StoreText.text = StoreNode.InnerText;
    250.                
    251.                 storeobj.StoreName = StoreNode.InnerText;
    252.  
    253.             }
    254.  
    255.             if (StoreNode.Name == "image")
    256.             {
    257.                 storeobj.StoreImage = StoreNode.InnerText;
    258.                 string SpriteFile = "StoreIcons/" + storeobj.StoreImage;
    259.  
    260.                 Sprite newSprite = Resources.Load<Sprite>(SpriteFile);
    261.                 Image StoreImage = NewStore.transform.Find("ImageButtonClick").GetComponent<Image>();
    262.                 StoreImage.sprite = newSprite;
    263.             }
    264.  
    265.             // Continue loading all the store properties from XML
    266.             if (StoreNode.Name == "BaseStoreProfit")
    267.                 storeobj.BaseStoreProfit = float.Parse(StoreNode.InnerText);
    268.             if (StoreNode.Name == "BaseStoreCost")
    269.                 storeobj.BaseStoreCost = float.Parse(StoreNode.InnerText);
    270.  
    271.             if (StoreNode.Name == "StoreTimer")
    272.             {
    273.                 storeobj.StoreTimer = float.Parse(StoreNode.InnerText);
    274.                 storeobj.BaseTimer = storeobj.StoreTimer;
    275.             }
    276.             if (StoreNode.Name == "StoreMultiplier")
    277.                 storeobj.StoreMultiplier = float.Parse(StoreNode.InnerText);
    278.             if (StoreNode.Name == "StoreTimerDivision")
    279.                 storeobj.StoreTimerDivision = int.Parse(StoreNode.InnerText);
    280.             if (StoreNode.Name == "StoreCount")
    281.                 storeobj.StoreCount = int.Parse(StoreNode.InnerText);
    282.             if (StoreNode.Name == "Manager")
    283.                 CreateManager(StoreNode, storeobj);
    284.             if (StoreNode.Name == "Upgrades")
    285.                 CreateUpgrades(StoreNode, storeobj);
    286.             if (StoreNode.Name == "id")
    287.                 storeobj.StoreID = int.Parse(StoreNode.InnerText);
    288.         }
    289.  
    290.         // Loop through all the upgrade nodes
    291.         void CreateUpgrades(XmlNode UpgradesNode, store Storeobj)
    292.         {
    293.             foreach (XmlNode UpgradeNode in UpgradesNode)
    294.             {
    295.  
    296.                 CreateUpgrade(UpgradeNode, Storeobj);
    297.  
    298.             }
    299.  
    300.         }
    301.  
    302.      
    303.         void CreateManager(XmlNode ManagerNode, store Storeobj)
    304.         {
    305.             float ManagerCost = 0f;
    306.             string ManagerName = "";
    307.             foreach (XmlNode ManagerInfo in ManagerNode)
    308.             {
    309.                 if (ManagerInfo.Name == "ManagerCost")
    310.                     ManagerCost = float.Parse(ManagerInfo.InnerText);
    311.                 if (ManagerInfo.Name == "ManagerName")
    312.                     ManagerName = ManagerInfo.InnerText;
    313.  
    314.             }
    315.  
    316.          
    317.  
    318.             Storeobj.CreateStoreManager(ManagerCost, ManagerName);
    319.  
    320.         }
    321.  
    322.         // Create each upgrade from the XML gamedata
    323.         void CreateUpgrade(XmlNode UpgradeNode, store Storeobj)
    324.         {
    325.            
    326.             float UpgradeMultiplier = 1f;
    327.             float UpgradeCost = 1f;
    328.             string UpgradeName = "";
    329.            
    330.            
    331.             foreach (XmlNode UpgradeInfo in UpgradeNode)
    332.             {
    333.  
    334.                 if (UpgradeInfo.Name == "UpgradeMultiplier")
    335.                     UpgradeMultiplier = float.Parse(UpgradeInfo.InnerText);
    336.                 if (UpgradeInfo.Name == "UpgradeCost")
    337.                     UpgradeCost = float.Parse(UpgradeInfo.InnerText);
    338.                 if (UpgradeInfo.Name == "UpgradeName")
    339.                     UpgradeName = UpgradeInfo.InnerText;
    340.  
    341.             }
    342.  
    343.  
    344.             /
    345.  
    346.             storeupgrade.CreateStoreUpgrade(UpgradeCost, UpgradeMultiplier, Storeobj, UpgradeName);
    347.  
    348.  
    349.          
    350.             UpgradeCount++;
    351.  
    352.         }
    353.  
    354.      
    355.         void LoadCurrencyData()
    356.         {
    357.             TextAsset CurrencyData = Resources.Load(CurrencyDataFile) as TextAsset;
    358.  
    359.             // Get the data from the csv file
    360.             string FileData = CurrencyData.text;
    361.  
    362.             // Get all the rows of data... \n finds the hidden return that separates the lines
    363.             string[] lines = FileData.Split("\n"[0]);
    364.  
    365.             // Create a new array list to hold our array
    366.             ArrayList CurrencyArray = new ArrayList();
    367.  
    368.             // We start at 6 because that is the millionth 'exponent'... this will be the first text description for an amount in the game
    369.             int Counter = 6;
    370.             // Load each row of the data
    371.             foreach (string line in lines)
    372.             {
    373.                 // This command breaks the comma delimited line of data into separate fields
    374.                 //string[] linedata = (line.Trim()).Split(","[0]);
    375.  
    376.                 // Create a new Curreny item to hold our data
    377.                 CurrencyItem CreateItem = new CurrencyItem();
    378.  
    379.                 // Set the key value we will lookup to find the correct currency description
    380.                 CreateItem.KeyVal = Counter;
    381.  
    382.                 try
    383.                 {
    384.                     // Format our exponent for this currency description. This is used to divide our currency amount so we can properly format the string
    385.                     CreateItem.ExpVal = double.Parse("1e" + (Counter).ToString());
    386.  
    387.                 }
    388.                 catch (OverflowException)
    389.                 {
    390.                     Debug.Log("Maximum Value reached, counter=" + Counter.ToString());
    391.                     break;
    392.                 }
    393.  
    394.              
    395.                 CreateItem.CurrencyName = line;
    396.                
    397.                
    398.                 CurrencyArray.Add(CreateItem);
    399.  
    400.              
    401.                 Counter = Counter + 3;
    402.             }
    403.  
    404.             // Store the array we have created in our game manager for access during gameplay
    405.             gamemanager.CurrencyArray = CurrencyArray;
    406.         }
    407.  
    408.  
    409.  
    410.     }
    411.  
    412.  
    413.     public class CurrencyItem
    414.     {
    415.         /
    416.         private int keyVal;
    417.  
    418.        
    419.         private double expVal;
    420.  
    421.         // Currency label (ie million, billion, trillion, etc)
    422.         private string currencyName;
    423.  
    424.         // Protect all our variables by keeping them private -- good practice to do throughout
    425.         public int KeyVal
    426.         {
    427.             get
    428.             {
    429.                 return keyVal;
    430.             }
    431.  
    432.             set
    433.             {
    434.                 keyVal = value;
    435.             }
    436.         }
    437.  
    438.         public double ExpVal
    439.         {
    440.             get
    441.             {
    442.                 return expVal;
    443.             }
    444.  
    445.             set
    446.             {
    447.                 expVal = value;
    448.             }
    449.         }
    450.  
    451.         public string CurrencyName
    452.         {
    453.             get
    454.             {
    455.                 return currencyName;
    456.             }
    457.  
    458.             set
    459.             {
    460.                 currencyName = value;
    461.             }
    462.         }
    463.     }
    464. }

    Second code:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using UnityEngine.UI;
    5. namespace BusinessTycoonSim
    6. {
    7.     public static class SaveGameData
    8.     {
    9.        
    10.         public static void Save()
    11.         {
    12.            
    13.             if (!gamemanager.DontSave)
    14.             {
    15.                 //Save the current system time as a string in the player prefs class
    16.                 PlayerPrefs.SetString("SaveDateTime", System.DateTime.Now.ToBinary().ToString());
    17.                 PlayerPrefs.SetString("Cash", gamemanager.GetCurrentBalance().ToString());
    18.                 PlayerPrefs.SetString("LifeTimeEarnings", gamemanager.LifeTimeEarnings.ToString());
    19.                 PlayerPrefs.SetInt("ActiveShareholders", gamemanager.ActiveShareholders);
    20.                 PlayerPrefs.SetInt("TotalShareholders", gamemanager.TotalShareholders);
    21.                 // Save Stores
    22.                 SaveStores();
    23.  
    24.                 // Save Upgrades
    25.                 SaveUpgrades();
    26.                 Save();
    27.                 // Update the preference file so we know we saved the game
    28.                 PlayerPrefs.SetInt("GameSaved",1);
    29.             }
    30.             else
    31.             {
    32.              
    33.                 PlayerPrefs.SetInt("GameSaved",0);
    34.             }
    35.  
    36.         }
    37.         static void SaveStores()
    38.         {
    39.  
    40.          
    41.             int counter = 1;
    42.             foreach (store StoreObj in gamemanager.StoreList)
    43.             {
    44.                
    45.                 PlayerPrefs.SetInt("storecount_" + counter, StoreObj.StoreCount);
    46.                 PlayerPrefs.SetFloat("storemultiple_" + counter, StoreObj.CurrentMultiplier);
    47.                 PlayerPrefs.SetFloat("storecurrenttimer_" + counter, StoreObj.GetCurrentTimer());
    48.                 PlayerPrefs.SetFloat("storetimer_" + counter, StoreObj.GetStoreTimer());
    49.                 int Unlocked = 0;
    50.                 if (StoreObj.StartTimer)
    51.                 {
    52.                     Unlocked = 1;
    53.  
    54.                 }
    55.                 PlayerPrefs.SetInt("storetimeractive_" + counter, Unlocked);
    56.  
    57.                 Unlocked = 0;
    58.                 if (StoreObj.ManagerUnlocked)
    59.                     Unlocked = 1;
    60.                 PlayerPrefs.SetInt("storemanagerunlocked_" + counter, Unlocked);
    61.  
    62.                 Unlocked = 0;
    63.                 if (StoreObj.StoreUnlocked)
    64.                     Unlocked = 1;
    65.                 PlayerPrefs.SetInt("storeunlocked_" + counter, Unlocked);
    66.  
    67.  
    68.                
    69.                 counter++;
    70.             }
    71.  
    72.  
    73.  
    74.         }
    75.  
    76.      
    77.         private static void SaveUpgrades()
    78.         {
    79.             int counter = 1;
    80.             foreach (storeupgrade StoreUpgrade in gamemanager.StoreUpgrades)
    81.             {
    82.                
    83.                 string stringKeyName = "storeupgradeunlocked_" + counter.ToString();
    84.              
    85.                 // Save upgrade unlock status
    86.                 int Unlocked = 0;
    87.                 if (StoreUpgrade.UpgradeUnlocked)
    88.                     Unlocked = 1;
    89.                 PlayerPrefs.SetInt(stringKeyName, Unlocked);
    90.                 Save();
    91.                 //Debug.Log("Save StoreUpgrade for key-" + stringKeyName + ":" + StoreUpgrade.UpgradeName + " Unlock Value=" + Unlocked.ToString());
    92.                 counter++;
    93.             }
    94.         }
    95.  
    96.     }
    97. }
     
  2. arfish

    arfish

    Joined:
    Jan 28, 2017
    Posts:
    782
    Hi,
    What makes you believe it doesn't work on Android?
     
  3. unity_MPhbdR7wb7LlCQ

    unity_MPhbdR7wb7LlCQ

    Joined:
    Sep 14, 2019
    Posts:
    15
    I know ,because I checked it on three phones, I deleted my application from the taskbar and it has not saved
     
  4. arfish

    arfish

    Joined:
    Jan 28, 2017
    Posts:
    782
  5. unity_MPhbdR7wb7LlCQ

    unity_MPhbdR7wb7LlCQ

    Joined:
    Sep 14, 2019
    Posts:
    15
    Im not uninstalled this app, im only deleted it, from task bar
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    As an aside, the above code will never work on Android.

    With the sole exception of using
    Application.persistentDataPath
    , none of the System.IO calls will work on Android.

    It appears that the above code is even used in your example so you might want to delete it.
     
  7. unity_MPhbdR7wb7LlCQ

    unity_MPhbdR7wb7LlCQ

    Joined:
    Sep 14, 2019
    Posts:
    15