Hi, I’m currently working on a small platformer game in which the goal is to complete levels as fast as possible. Hence, I want to display the current time and best time achieved. The current time works fine, the problem is the save and display of the best time.
public class Timer_Best : MonoBehaviour
{
//VARIABLES
public static Timer_Best instance;
private bool timerActive = false;
float currentTime;
float bestTime;
public TMP_Text currentTimeText;
public TMP_Text bestTimeText;
//UPDATES
private void Awake()
{
instance = this;
}
private void Start()
{
currentTime = 0f;
//Display BestTime
bestTime = PlayerPrefs.GetFloat("best");
bestTimeText.text = "Best: " + bestTime.ToString(@"mm\:ss\:ff");
}
private void Update()
{
//Current Time
if (Input.anyKey)
{
BeginTimer();
}
if (timerActive == true)
{
currentTime += Time.deltaTime;
}
TimeSpan time = TimeSpan.FromSeconds(currentTime);
currentTimeText.text = "Current: " + time.ToString(@"mm\:ss\:ff");
if (timerActive == false)
{
EndTimer();
}
}
//METHODS
public void BeginTimer()
{
timerActive = true;
}
public void EndTimer()
{
timerActive = false;
//BestTime Update
if (PlayerPrefs.HasKey("best"))
{
Debug.Log("Current best" + PlayerPrefs.GetFloat("best"));
if (currentTime < PlayerPrefs.GetFloat("best"))
{
Debug.Log("Saved new timer value" + currentTime);
PlayerPrefs.SetFloat("best", currentTime);
}
}
}
}
I am currently calling the EndTimer method from another script with OnCollision like so:
if (collision.gameObject.tag == "endTile")
{
timer.EndTimer();
}
The best time achieved is never saved nor displayed (even when trying to debug with a PressKeyDown line). Can somebody point out my mistakes ? Thanks !!!