I’m new to Unity and to coding in general and I was creating a speedrunning game and I wanted the player’s best time to show up on screen.
The code I’m using right now runs and doesn’t have any errors but neither the Best Time text nor the Best variable is updating.
I have a strong feeling that this has something to do with the variable types. I had to create a new variable “e” to convert a string value to a float value but even though it works, I think it might still be the problem since the text and variable seem to refuse to be assigned to “e”.
Anyway, this is my code and I hope someone can help me out. Thank you!
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine;
public class Timer : MonoBehaviour
{
private float seconds;
public Text timerText;
private float startTime;
private bool finished = false;
public bool Begin2;
public Text bestTime2;
public float bestTime = 999;
public float e;
// Start is called before the first frame update
void Start()
{
startTime = Time.time;
Begin2 = false;
timerText.text = "0.00";
}
// Update is called once per frame
void Update()
{
if(Begin2){
if(finished){
return;
}
float t = Time.time - startTime;
string minutes = ((int) t / 60).ToString();
string seconds = (t % 60).ToString("f2");
e = float.Parse(seconds);
timerText.text = seconds;
if(finished){
if(e < bestTime){
bestTime = e;
bestTime2.text = "Best: " + e;
}
}
}
}
public void Finish()
{
finished = true;
}
public void Begin()
{
Begin2 = true;
finished = false;
startTime = Time.time;
}
}