Firstly, I’m not sure I’m posting in this in the right sub-forum, I’m kind of confused by the different UIs available here. I’m running Unity 2020.3.30f1 and talking about the objects created by adding UI->Text in the interface.
I want to have a UI element that writes out the value of some variable that, for convenience, I’m storing in a static class. The code looks something like
class MyTextClass : MonoBehaviour
{
public Text DisplayText;
void Start() => DisplayText.text = "";
void Update()
{
DisplayText.text = $"Value is {MyStaticClass.Value}";
}
}
I was wondering however if this is inefficient because I’m forcing it to be re-rendered every frame? I’m guessing that assigning to Text.text might call something behind the scene that makes the engine render, but I really have no idea how it actually works and haven’t found anything in the docs. All that to ask, is it considerably more efficient to cache things I don’t assign to Text.text as much, like this? Obviously one single small block of text isn’t going to kill performance, but I’ll have many elements like this and I’d like to get into good habits early on.
class MyTextClass : MonoBehaviour
{
public Text DisplayText;
private int CacheValue;
void Start() => DisplayText.text = "";
void Update()
{
if (CacheValue != MyStaticClass.Value)
{
CacheValue = MyStaticClass.Value;
DisplayText.text = $"Value is {CacheValue}";
}
}
}
Or am I doing this all wrong and I should be “pushing” the MyStaticClass.Value to the UI every time it changes? If so, some pointers to an example on how to do it would be great.
On a minor, related, note: my IDE (VisualStudio 2022) complains with Warning S1104 that DisplayText is a field and tells me to encapsulate it as a property. When I do that, however, the script is no longer recognised by Unity as having text to display. Is there a way out a this?