Interesting behaviour when trying to display a String in OnGUI()

Hi,

Let’s take a particular case into consideration:

class A : MonoBehaviour
{
private string ToDisplay = “”;

private void Update()
{
}

private void OnGUI()
{
GUI.Box(somepositionhere, ToDisplay);
ToDisplay = “”;
}

/This gets called from another class’ Update() function - there’s an instance of A in that class/
public void SetString(string NewString)
{
ToDisplay = NewString;
}
}

If I run the code, there’s nothing shown on the GUI (no box). If I replace ToDisplay with some constant string like “hello”, the box gets drawn, with the appropriate text.

HOWEVER - If I do this:
class A : MonoBehaviour
{
private string ToDisplay = “”;

private void Update()
{
ToDisplay = “”;
}

private void OnGUI()
{
GUI.Box(somepositionhere, ToDisplay);
}

/This gets called from another class’ Update() function - there’s an instance of A in that class/
public void SetString(string NewString)
{
ToDisplay = NewString;
}
}

The box GETS DISPLAYED, with the correct content (the text contained by the ToDisplay object).

Why is that? I suspect that GUI.Box(…) just queues the items to be shown, so when the actual GUI drawing takes place, the text content is taken on the spot, from the ToDisplay string that happened to be updated to the empty string in the meantime.
Of course, I’d like a more documented answer to this, as my explanation is just a hunch.

OnGUI is called multiple times per frame so your text string is getting set to “” before you ever get to display it. Each call to OnGUI is for an event - the first one will probably be layout, the repaint then further calls for mouse etc.

Update is only called once per frame.

If you want the code in OnGUI try something like:

if(Event.current.type == EventType.repaint) ToDisplay = "";