ludumdare50/Assets/Scripts/GameTimer.cs
2022-04-03 20:17:45 -04:00

66 lines
1.1 KiB
C#

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<TMP_Text>();
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;
}
}