- Home /
How do I constantly update a variable that is displayed in a UI text component?
I have a vehicle level that I set up using the Standard Assets vehicle sample level. The CarController script contains a float named Revs that I want to constantly update in the UI while driving around. I have this set up in the CarController script by converting it to a string and assigning it to a text variable which is linked in to the UI. This displays the variable but it only briefly flickers on-screen every so often, how can I make Unity constantly update the variable in the UI so I can always see what the current value is?
link text
Try out : void Update () { SetRevText(); }
Further you can update the revText via coroutine also.
Answer by Brijs · Jun 16, 2016 at 01:35 PM
More efficient way
1) Make Property of Revs variable.
2) In set{} block of property call method to change revsText.text
For example:
private int revs;
public int Revs
{
get { return revs; }
set
{
revs = value;
ReflectValue(revs);
}
}
public void ReflectValue(int revs)
{
revText.text = revs.ToString();
}
Here you can use event instead of direct method ReflectValue() to have more decoupled and extendible code
Answer by EpiFouloux · Jun 15, 2016 at 07:42 AM
void Update()
{
revtText.text = "RPM: " + value.ToString();
}
// or
void Start()
{
StartCoroutine(Cor_show_level());
}
private IEnumerator Cor_show_level()
{
while (true)
{
revtText.text = "RPM: " + value.ToString();
yield return new WaitForSeconds(time_between_two_prints);
}
}
EDIT : I believe that the constant updating idea is not great : You should update the text only when you update the value to reduce computing