using System; using TMPro; using UnityEngine; public class GameTimer : MonoBehaviour { TMP_Text label; float timer; float highScore; bool stopped; public bool Stopped { get => stopped; set { stopped = value; UpdateLabel(); } } public bool ShowHighScore { get => showHighScore; set { showHighScore = value; UpdateLabel(); } } bool showHighScore; public const string HIGH_SCORE_KEY = "High Score"; void Awake() { label = GetComponent(); timer = 0f; highScore = PlayerPrefs.GetFloat(HIGH_SCORE_KEY); Stopped = true; } void Update() { if (Stopped) return; timer += Time.deltaTime; SaveHighScore(); UpdateLabel(); } void UpdateLabel() { label.text = TimeSpan.FromSeconds(timer) .ToString(@"mm\:ss"); if (ShowHighScore) label.text += "\nBest Time: " + TimeSpan.FromSeconds(highScore) .ToString(@"mm\:ss"); } public void SaveHighScore() { if (timer <= highScore) return; PlayerPrefs.SetFloat(HIGH_SCORE_KEY, timer); highScore = timer; } public void ResetHighScore() { PlayerPrefs.DeleteKey(HIGH_SCORE_KEY); highScore = 0f; } }