- Home /
Text UI is not being assigned
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;
}
}
Answer by Jaxcap · Dec 22, 2020 at 08:59 AM
I assume that you want the best time to be updated if finished = true? If the structure of your code is what I think it is (a little hard to tell due to formatting), I think this code:
if(e < bestTime){
bestTime = e;
bestTime2.text = "Best: " + e;
}
might not get used ever because you already have that other if(finished) block above that will just return before you can get there.
Answer by lvskiprof · Dec 22, 2020 at 09:36 PM
Since you have made it public, are you sure that some other code is not modifying it?
You should avoid using public data as much as possible.
If you use [SerializeField] you can view it in the Inspector without making it public while you run the program. I assume you have linked it in the Unity Editor to the text element in your game.
Your answer
Follow this Question
Related Questions
Add up updating float 2 Answers
Multiple Rich Text Not Working 1 Answer
Selecting a part of string in input field 1 Answer