Advertisement
LeeMace

Save High Score and Player across Sessions

Jan 11th, 2023
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.30 KB | Gaming | 0 0
  1. 1. Create a new Scene and call it "Start Menu". Create there -
  2.  
  3.  - Text Object for Best Score
  4.  - Text Input Field
  5.  - Start Button
  6.  - Quit Button
  7.  
  8. In Inspector (in the text of Placeholder of the InputField) tape "Tape your name..."
  9.  
  10. 2. Then, create a new Empty Object in the Start Menu Scene and call it Player Data Handle. Now, we need to create a new script to be the static class where we’ll store the data you want to persist between scenes. So, create a new script and call it PlayerDataHandle (and attach it):
  11.  
  12.  
  13. using System.Collections;
  14. using System.Collections.Generic;
  15. using UnityEngine;
  16.  
  17. public class PlayerDataHandle : MonoBehaviour
  18. {
  19.     //Static Class for save the current player data;
  20.     //Singleton pattern
  21.  
  22.     public static PlayerDataHandle Instance;
  23.  
  24.     public string PlayerName;
  25.  
  26.     public int Score;
  27.  
  28.     private void Awake()
  29.     {
  30.         //we dont actually need this if statement because when we are in the Main Scene we cant return to the Start Menu Scene where the Player Data Handle Object already exists.
  31.         if (Instance != null)
  32.         {
  33.             Destroy(gameObject);
  34.         }
  35.         Instance = this;
  36.         DontDestroyOnLoad(gameObject);
  37.     }
  38. }
  39.  
  40.  
  41. 3. Create MenuUIHandler.cs script and attach it to the Canvas in the Start Menu Scene:
  42.  
  43. using System.Collections;
  44. using System.Collections.Generic;
  45. using UnityEngine;
  46. using UnityEngine.SceneManagement;
  47. using UnityEngine.UI;
  48. using UnityEditor;
  49. public class MenuUIHandler : MonoBehaviour
  50. {
  51.     //This is the handler of the main menu scene
  52.  
  53.     [SerializeField] Text PlayerNameInput;
  54.  
  55.     public void StartGame()
  56.     {
  57.         SceneManager.LoadScene(1);
  58.     }
  59.  
  60.     public void SetPlayerName()
  61.     {
  62.         PlayerDataHandle.Instance.PlayerName = PlayerNameInput.text;
  63.     }
  64.  
  65.     public void ExitGame()
  66.     {
  67. #if UNITY_EDITOR
  68.         EditorApplication.ExitPlaymode();
  69. #else
  70.         Application.Quit();
  71. #endif
  72.     }
  73. }
  74.  
  75.  
  76.  
  77. 4.
  78. 4.1 - Select Canvas in Inspector. In the window for Player Name Input assign the Text component of the InputField.
  79. 4.2 - Select InputField in Inspector. On End Edit(String) - Assign the current Canvas  and choose the function - MenuUIHandler - SetPlayerName().
  80. 4.3 - Select Start Button in Inspector. On Click() - Assign the current canvas  and choose the function - MenuUIHandler - StartGame().
  81. 4.4 - Select Quit Button in Inspector. On Click() - Assign the current canvas  and choose the function - MenuUIHandler - ExitGame().
  82.  
  83.  
  84.  
  85.  
  86.  
  87. 5. Create a new Empty Object in the Start Menu Scene and call it LoadGameRank. Create a new script and call it LoadGameRank (and attach it):
  88.  
  89. using System.Collections;
  90. using System.Collections.Generic;
  91. using UnityEngine;
  92. using UnityEngine.SceneManagement;
  93. using UnityEngine.UI;
  94. using System.IO;
  95.  
  96. public class LoadGameRankScript : MonoBehaviour
  97. {
  98.  
  99.     //Fields for display the player info
  100.  
  101.     public Text BestPlayerName;
  102.  
  103.  
  104.     //Static variables for holding the best player data
  105.     private static int BestScore;
  106.     private static string BestPlayer;
  107.  
  108.  
  109.     private void Awake()
  110.     {
  111.         LoadGameRank();
  112.     }
  113.  
  114.  
  115.  
  116.     private void SetBestPlayer()
  117.     {
  118.         if (BestPlayer == null && BestScore == 0)
  119.         {
  120.             BestPlayerName.text = "";
  121.         }
  122.         else
  123.         {
  124.             BestPlayerName.text = $"Best Score - {BestPlayer}: {BestScore}";
  125.         }
  126.  
  127.     }
  128.  
  129.     public void LoadGameRank()
  130.     {
  131.         string path = Application.persistentDataPath + "/savefile.json";
  132.  
  133.         if (File.Exists(path))
  134.          {
  135.             string json = File.ReadAllText(path);
  136.             SaveData data = JsonUtility.FromJson<SaveData>(json);
  137.  
  138.             BestPlayer = data.TheBestPlayer;
  139.             BestScore = data.HighiestScore;
  140.             SetBestPlayer();
  141.         }
  142.     }
  143.  
  144.     [System.Serializable]
  145.     class SaveData
  146.     {
  147.         public int HighiestScore;
  148.         public string TheBestPlayer;
  149.     }
  150. }
  151.  
  152. 6. Change the MainManager script this way:
  153.  
  154. using System.Collections;
  155. using System.Collections.Generic;
  156. using UnityEngine;
  157. using UnityEngine.SceneManagement;
  158. using UnityEngine.UI;
  159. using System.IO;
  160.  
  161. public class MainManager : MonoBehaviour
  162. {
  163.     public Brick BrickPrefab;
  164.     public int LineCount = 6;
  165.     public Rigidbody Ball;
  166.  
  167.     public Text ScoreText;
  168.  
  169.     //Fields for display the player info
  170.     public Text CurrentPlayerName;
  171.     public Text BestPlayerNameAndScore;
  172.  
  173.     public GameObject GameOverText;
  174.  
  175.     private bool m_Started = false;
  176.     private int m_Points;
  177.  
  178.     private bool m_GameOver = false;
  179.  
  180.     //Static variables for holding the best player data
  181.     private static int BestScore;
  182.     private static string BestPlayer;
  183.  
  184.  
  185.     private void Awake()
  186.     {
  187.         LoadGameRank();
  188.     }
  189.     // Start is called before the first frame update
  190.     void Start()
  191.     {
  192.         const float step = 0.6f;
  193.         int perLine = Mathf.FloorToInt(4.0f / step);
  194.  
  195.         int[] pointCountArray = new[] { 1, 1, 2, 2, 5, 5 };
  196.         for (int i = 0; i < LineCount; ++i)
  197.         {
  198.             for (int x = 0; x < perLine; ++x)
  199.             {
  200.                 Vector3 position = new Vector3(-1.5f + step * x, 2.5f + i * 0.3f, 0);
  201.                 var brick = Instantiate(BrickPrefab, position, Quaternion.identity);
  202.                 brick.PointValue = pointCountArray[i];
  203.                 brick.onDestroyed.AddListener(AddPoint);
  204.             }
  205.         }
  206.  
  207.         CurrentPlayerName.text = PlayerDataHandle.Instance.PlayerName;
  208.  
  209.         SetBestPlayer();
  210.     }
  211.  
  212.     private void Update()
  213.     {
  214.         if (!m_Started)
  215.         {
  216.             if (Input.GetKeyDown(KeyCode.Space))
  217.             {
  218.                 m_Started = true;
  219.                 float randomDirection = Random.Range(-1.0f, 1.0f);
  220.                 Vector3 forceDir = new Vector3(randomDirection, 1, 0);
  221.                 forceDir.Normalize();
  222.  
  223.                 Ball.transform.SetParent(null);
  224.                 Ball.AddForce(forceDir * 2.0f, ForceMode.VelocityChange);
  225.             }
  226.         }
  227.         else if (m_GameOver)
  228.         {
  229.             if (Input.GetKeyDown(KeyCode.Space))
  230.             {
  231.                 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
  232.             }
  233.         }
  234.     }
  235.  
  236.     void AddPoint(int point)
  237.     {
  238.         m_Points += point;
  239.         PlayerDataHandle.Instance.Score = m_Points;
  240.         ScoreText.text = $"Score : {m_Points}";
  241.     }
  242.  
  243.     public void GameOver()
  244.     {
  245.         m_GameOver = true;
  246.         CheckBestPlayer();
  247.         GameOverText.SetActive(true);
  248.     }
  249.  
  250.     private void CheckBestPlayer()
  251.     {
  252.         int CurrentScore = PlayerDataHandle.Instance.Score;
  253.  
  254.         if (CurrentScore > BestScore)
  255.         {
  256.             BestPlayer = PlayerDataHandle.Instance.PlayerName;
  257.             BestScore = CurrentScore;
  258.  
  259.             BestPlayerNameAndScore.text = $"Best Score - {BestPlayer}: {BestScore}";
  260.  
  261.             SaveGameRank(BestPlayer, BestScore);
  262.         }
  263.     }
  264.  
  265.     private void SetBestPlayer()
  266.     {
  267.         if (BestPlayer == null && BestScore == 0)
  268.         {
  269.             BestPlayerNameAndScore.text = "";
  270.         }
  271.         else
  272.         {
  273.             BestPlayerNameAndScore.text = $"Best Score - {BestPlayer}: {BestScore}";
  274.         }
  275.  
  276.     }
  277.  
  278.     public void SaveGameRank(string bestPlaterName, int bestPlayerScore)
  279.     {
  280.         SaveData data = new SaveData();
  281.  
  282.         data.TheBestPlayer = bestPlaterName;
  283.         data.HighiestScore = bestPlayerScore;
  284.  
  285.         string json = JsonUtility.ToJson(data);
  286.         File.WriteAllText(Application.persistentDataPath + "/savefile.json", json);
  287.     }
  288.  
  289.     public void LoadGameRank()
  290.     {
  291.         string path = Application.persistentDataPath + "/savefile.json";
  292.  
  293.         if (File.Exists(path))
  294.         {
  295.             string json = File.ReadAllText(path);
  296.             SaveData data = JsonUtility.FromJson<SaveData>(json);
  297.  
  298.             BestPlayer = data.TheBestPlayer;
  299.             BestScore = data.HighiestScore;
  300.         }
  301.     }
  302.  
  303.     [System.Serializable]
  304.     class SaveData
  305.     {
  306.         public int HighiestScore;
  307.         public string TheBestPlayer;
  308.     }
  309. }
  310.  
  311. 7.
  312. 7.1. Create a new Text Object in the Main Scene and call it CurrentName.
  313. 7.2. Select Main Manager in Inspector and check that you have assigned text objexts for Score Text, Current Player Name and Best Player Name and Score.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement