Search Unity

Using a 'Save Manager' to save my PlayerPrefs...

Discussion in 'Scripting' started by Plott, Oct 1, 2014.

  1. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    Hello!

    Im using a SaveManager Script that saves my player prefs. The problem is I can't figure out how to write my "High score" script correctly

    Here is the score part

    Code (CSharp):
    1.    using UnityEngine;
    2.     using System.Collections;
    3.    
    4.     public class GameOverScript : MonoBehaviour {
    5.    
    6.         public LevelGenerator levelGenerator;
    7.    
    8.         public TextMesh coinGameOverAmmount;
    9.    
    10.         public TextMesh distanceGameOverAmmount;
    11.    
    12.         public TextMesh highScoreGameOver;
    13.    
    14.         public void Setup(int coins, int distance)
    15.    
    16.         {
    17.             coinGameOverAmmount.text = coins.ToString ();
    18.    
    19.             distanceGameOverAmmount.text = distance + "M";
    20.              // This is where Im having issues. SaveManger.bestDistance isn't working
    21.             highScoreGameOver.text = SaveManager.bestDistance;
    22.        
    23.             if (SaveManager.bestDistance < levelGenerator.CurrentDistance ())
    24.                 SaveManager.bestDistance = levelGenerator.CurrentDistance ();
    25.         }
    26.     }
    Here is my save manager script

    Code (CSharp):
    1. public static class SaveManager : object
    2. {
    3.     public static int coinAmmount = 1500;                   //The ammount of coins the player has
    4.     public static int bestDistance = 0;                     //The best distance the player has reached
    5.  
    6.     public static int punches = 0;                    
    7.     public static void LoadData()
    8.     {
    9.         //If found the coin ammount data, load the datas
    10.         if (!PlayerPrefs.HasKey("Coin ammount"))
    11.             SaveData();
    12.         else
    13.         {
    14.             coinAmmount = PlayerPrefs.GetInt("Coin ammount");
    15.             bestDistance = PlayerPrefs.GetInt("Best Distance");
    16.  
    17.             punches = PlayerPrefs.GetInt("Punches");
    18.  
    19.             audioEnabled = PlayerPrefs.GetInt("AudioEnabled");
    20.         }
    21.     }
    22.  
    23.     //Saves the player data
    24.     public static void SaveData()
    25.     {
    26.         PlayerPrefs.SetInt("Coin ammount", coinAmmount);
    27.         PlayerPrefs.SetInt("Best Distance", bestDistance);
    28.  
    29.         PlayerPrefs.SetInt("Punches", punches);
    30.  
    31.         PlayerPrefs.SetInt("AudioEnabled", audioEnabled);
    32.  
    33.         PlayerPrefs.Save();
    34.     }
     
  2. iMob

    iMob

    Joined:
    Apr 9, 2014
    Posts:
    55
    Don´t tested your script, but you try to set the string highScoreGameOver.text to the int value of SaveManager.bestDistance.
    To convert an int value to a string you can use highScoreGameOver.text = SaveManager.bestDistance.ToString();
     
  3. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    OHHHHH duhhhh, its works now! thanks so much! I was stump!
     
  4. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    Ok So it works when I'm in the game. But when i test it on my iPhone is doesn't save to my device when i quit the app and load again... any ideas?

    I also adjusted my code to look like this now

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GameOverScript : MonoBehaviour {
    5.  
    6.     public LevelGenerator levelGenerator;
    7.  
    8.     public TextMesh coinGameOverAmmount;
    9.  
    10.     public TextMesh distanceGameOverAmmount;
    11.  
    12.     public TextMesh highScoreGameOver;
    13.  
    14.  
    15.     public void Setup(int coins, int distance)
    16.  
    17.     {
    18.         coinGameOverAmmount.text = coins.ToString ();
    19.  
    20.         distanceGameOverAmmount.text = distance + "M";
    21.  
    22.         highScoreGameOver.text = SaveManager.bestDistance.ToString () + "M";
    23.     }
    24.  
    25.  
    26. }
     
  5. iMob

    iMob

    Joined:
    Apr 9, 2014
    Posts:
    55
    If it works on PC/Mac it should also work on mobile. But not very fast.
    One idea:
    Where do you call SaveData? Don't do it every frame in Update() or somewhere else highly frequent. Mobile is too slow to save every frame. Just save if nessessery.
    To save if the user quit application you can use:

    Public void OnApplicationQuit() { SaveData(); }


    (Sorry no code tags, i'm on mobile now)
     
  6. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    Im going to try us on app quit. i wasn't saving in update, but was saving on death. technically it would make more sense on quoting though. thanks for your help, ill let you know if i fix it.
     
  7. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    @iMob

    Ok I got saving coins and distance working, but here is a problem I don't understand.

    At the main screen i have coin amount texts and best distances amounts.

    Now if you play the game they work, coins are added to your old amount and distance is replaced if its the highest.

    BUT

    when you first load the game that same main screen comes up with zero loaded data. Any idea how to load data at the beginning? I don't know what I'm doing wrong.
     
    Last edited: Oct 2, 2014
  8. iMob

    iMob

    Joined:
    Apr 9, 2014
    Posts:
    55
    I do not know all your scripts. No idea where the problem is.
    Can you post the "main" game script, which call LoadData() and SaveData() ?
    Or you can post me your project as pm and I check it.
     
  9. Plott

    Plott

    Joined:
    May 12, 2014
    Posts:
    94
    @iMob

    My level Manager here is what is running everything basically

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class LevelManager : MonoBehaviour
    5. {
    6.     public PlayerManager playerManager;                 //Holds a link to the Player Manager
    7.     public GUIMMManager guiManager;                       //Holds a link to the GUI Manager
    8.     public LevelGenerator levelGenerator;               //Holds a link to the Level Generator
    9.     public MissionManager missionManger;
    10.  
    11.     public enum LevelState { MainMenu, Tutorial, PlayMode, GameOver }   //Holds the possible level states
    12.  
    13.     static LevelManager myInstance;                                     //Stores a reference to this script
    14.  
    15.     private int currentScore;                                           //Stores the current score
    16.     private bool paused;                                                //True, if the game is paused
    17.     private int collectedCoins;
    18.     private int collectedBattery;
    19.  
    20.     //Returns the instance
    21.     public static LevelManager Instance { get { return myInstance; } }
    22.     //Stores the current level state
    23.     public static LevelState levelState = LevelState.MainMenu;
    24.  
    25.     void Start ()
    26.     {
    27.         myInstance = this;
    28. //        currentScore = 0;
    29. //        collectedCoins = 0;
    30.  
    31.         SaveManager.LoadData ();
    32.         SaveManager.LoadMissionData ();
    33.  
    34.         SaveManager.SaveData ();
    35.         SaveManager.ResetMissions ();
    36.  
    37.         missionManger.LoadData ();
    38.  
    39.  
    40.     }
    41.  
    42.  
    43.     public void Restart()
    44.     {
    45.         currentScore = 0;
    46.         collectedCoins = 0;
    47.  
    48.         levelGenerator.Reset();
    49.         playerManager.Reset();
    50.         guiManager.Reset();
    51.  
    52.         levelState = LevelState.MainMenu;
    53.     }
    54.  
    55.  
    56.     public void QuitToMain()
    57.     {
    58.         currentScore = 0;
    59.  
    60.         guiManager.ResetMainMenu();
    61.         playerManager.Reset();
    62.         levelGenerator.Reset();
    63.  
    64.  
    65.  
    66.         levelState = LevelState.MainMenu;
    67.  
    68.     }
    69.  
    70.  
    71.     public void StartLevel()
    72.     {
    73.         collectedCoins = 0;
    74.  
    75.         levelState = LevelState.PlayMode;
    76.  
    77.         levelGenerator.StartToGenerate();
    78.         IncreaseScore ();
    79.  
    80.         playerManager.collider2D.enabled = true;
    81.  
    82.     }
    83.  
    84.     public void PauseGame()
    85.     {
    86.         GUIMMManager.Instance.SetPauseState(true);
    87.         PlayerManager.Instance.SetPauseState(true);
    88.         LevelGenerator.Instance.SetPauseState(true);
    89.     }
    90.  
    91.     public void ResumeGame()
    92.     {
    93.         GUIMMManager.Instance.SetPauseState(false);
    94.         PlayerManager.Instance.SetPauseState(false);
    95.         LevelGenerator.Instance.SetPauseState(false);
    96.     }
    97.  
    98.     public void CrashEvent()
    99.     {
    100.         Debug.Log ("DEATH");
    101.  
    102.         guiManager.GameOver();
    103.  
    104.         //Pause the level generator, and set the level state
    105.         LevelGenerator.Instance.SetPauseState(true);
    106.  
    107.         levelState = LevelState.GameOver;
    108.  
    109.         playerManager.collider2D.enabled = false;
    110.  
    111.     }
    112.  
    113.     public void IncreaseScore()
    114.     {
    115.         currentScore++;
    116.  
    117.     }
    118.  
    119.     public void CoinCollected (Vector2 contactPoint)
    120.     {
    121.         Debug.Log ("COIN!");
    122.         collectedCoins++;
    123.  
    124.         GUIMMManager.Instance.UpdateCoins(collectedCoins);
    125.  
    126.  
    127.     }
    128.  
    129.     public int CollectedCoins()
    130.     {
    131.         return collectedCoins;
    132.     }
    133.  
    134.     public void BatteryCollected (Vector2 contactPoint)
    135.     {
    136.         Debug.Log ("Battery!");
    137.         GUIMMManager.Instance.UpdateBattery ();
    138.     }
    139.  
    140.     public void LevelEnded ()
    141.     {
    142.         SaveStats ();
    143.  
    144. //        missionManager.SaveData ();
    145. //        missionManager.LoadData ();
    146.  
    147.     }
    148.  
    149.     public void Collision(string collidedWith, Vector2 contactPoint)
    150.     {
    151.         levelGenerator.AddExplosionParticle (contactPoint);
    152. //        missionManger.CollisionEvent (collidedWith);
    153.     }
    154.  
    155.  
    156. /*
    157.     public void Collision(Vector2 contactPoint)
    158.     {
    159.         levelGenerator.AddExplosionParticle (contactPoint);
    160.         //        missionManger.CollisionEvent (collidedWith);
    161.     }
    162. */
    163.  
    164.  
    165.     public void OnApplicationQuit()
    166.     {
    167.         SaveManager.SaveData();
    168.     }
    169.  
    170.     private void SaveStats ()
    171.     {
    172.         if (SaveManager.bestDistance < levelGenerator.CurrentDistance ())
    173.                         SaveManager.bestDistance = levelGenerator.CurrentDistance ();
    174.  
    175.         SaveManager.coinAmmount += collectedCoins;
    176.  
    177.         SaveManager.SaveData ();
    178.  
    179.     }
    180. }
    181.  
    my save manager

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public static class SaveManager : object
    5. {
    6.     public static int coinAmmount = 0;                   //The ammount of coins the player has
    7.     public static int bestDistance = 0;                     //The best distance the player has reached
    8.  
    9.     public static int punches = 0;                       //The ammount of extra speed power ups the player has
    10.  
    11.  
    12.     public static int audioEnabled = 1;
    13.  
    14.     public static int[] missionID;                          //Mission 1, 2 and 3 ID
    15.     public static int[] missionData;                        //Mission 1, 2 and 3 Data
    16.  
    17.     public static string missionDataString = "";            //Saved mission data string
    18.  
    19.     //Loads the player data
    20.     public static void LoadData()
    21.     {
    22.         //If found the coin ammount data, load the datas
    23.         if (!PlayerPrefs.HasKey("Coin ammount"))
    24.  
    25.             SaveData();
    26.         else
    27.  
    28.         {
    29.             coinAmmount = PlayerPrefs.GetInt("Coin ammount");
    30.             bestDistance = PlayerPrefs.GetInt("Best Distance");
    31.  
    32.             punches = PlayerPrefs.GetInt("Punches");
    33.  
    34.             audioEnabled = PlayerPrefs.GetInt("AudioEnabled");
    35.         }
    36.     }
    37.     //Saves the player data
    38.     public static void SaveData()
    39.     {
    40.         PlayerPrefs.SetInt("Coin ammount", coinAmmount);
    41.         PlayerPrefs.SetInt("Best Distance", bestDistance);
    42.  
    43.         PlayerPrefs.SetInt("Punches", punches);
    44.  
    45.         PlayerPrefs.SetInt("AudioEnabled", audioEnabled);
    46.  
    47.         PlayerPrefs.Save();
    48.     }
    49.     //Loads the mission data
    50.     public static void LoadMissionData()
    51.     {
    52.         missionID = new int[3] { -1, -1, -1 };
    53.         missionData = new int[3] { 0, 0, 0 };
    54.  
    55.         if (!PlayerPrefs.HasKey("Missions"))
    56.         {
    57.             SaveMissionData();
    58.         }
    59.         else
    60.         {
    61.             missionDataString = PlayerPrefs.GetString("Missions");
    62.  
    63.             missionID[0] = PlayerPrefs.GetInt("Mission1");
    64.             missionID[1] = PlayerPrefs.GetInt("Mission2");
    65.             missionID[2] = PlayerPrefs.GetInt("Mission3");
    66.  
    67.             missionData[0] = PlayerPrefs.GetInt("Mission1Data");
    68.             missionData[1] = PlayerPrefs.GetInt("Mission2Data");
    69.             missionData[2] = PlayerPrefs.GetInt("Mission3Data");
    70.         }
    71.     }
    72.     //Saves the mission data
    73.     public static void SaveMissionData()
    74.     {
    75.         PlayerPrefs.SetInt("Mission1", missionID[0]);
    76.         PlayerPrefs.SetInt("Mission2", missionID[1]);
    77.         PlayerPrefs.SetInt("Mission3", missionID[2]);
    78.  
    79.         PlayerPrefs.SetInt("Mission1Data", missionData[0]);
    80.         PlayerPrefs.SetInt("Mission2Data", missionData[1]);
    81.         PlayerPrefs.SetInt("Mission3Data", missionData[2]);
    82.  
    83.         PlayerPrefs.SetString("Missions", missionDataString);
    84.     }
    85.     //Reset mission data
    86.     public static void ResetMissions()
    87.     {
    88.         missionID = new int[3] { -1, -1, -1 };
    89.         missionData = new int[3] { 0, 0, 0 };
    90.  
    91.         missionDataString = "";
    92.  
    93.         SaveMissionData();
    94.     }
    95. }

    Basically here in level manager is where i think the issue is.

    Code (CSharp):
    1.     void Start ()
    2.     {
    3.         myInstance = this;
    4. //        currentScore = 0;
    5. //        collectedCoins = 0;
    6.         SaveManager.LoadData ();
    7.         SaveManager.LoadMissionData ();
    8.         SaveManager.SaveData ();
    9.         SaveManager.ResetMissions ();
    10.         missionManger.LoadData ();
    11.     }
    Im pretty lost now, so i just picked up a different problem to solve for now. thanks so much for your help/replies.
     
  10. iMob

    iMob

    Joined:
    Apr 9, 2014
    Posts:
    55
    You load data, save data, load it again. All very quickly. I´m not sure that a mobile device can handle it so fast.
    Try to integrate some yield WaitForSeconds() between load and save and load again.
    I don´t know if this solve the problem. But I would try it first.

    Code (csharp):
    1.  
    2.  
    3.  
    4.    void Start ()
    5.    {
    6.         myInstance = this;
    7. //        currentScore = 0;
    8. //        collectedCoins = 0;
    9.         SaveManager.LoadData ();
    10.         SaveManager.LoadMissionData ();
    11.         yield WaitForSeconds(0.5f);
    12.  
    13.         SaveManager.SaveData ();
    14.         SaveManager.ResetMissions ();
    15.         yield WaitForSeconds(0.5f);
    16.  
    17.         missionManger.LoadData ();
    18.     }
    19.  
    20.