If statement with OnGUI

Trying to create an if statement in the OnGUI method. Here is my code.

bool refresh = false;

    void Update()
	{
		if(Input.GetKeyDown(KeyCode.Space))
		{
			refresh = true;
			print ("update gets it");
		}
	}

	void OnGUI() 
	{

		if(refresh)
		{
			GUI.Label(new Rect(10, 10, 100, 20), "Hello World!",style);
			print ("ongui gets it");
			refresh = false;
			
		}

	}

What is interesting is that “ongui gets it” is printed. but the label is not printed on the screen.

Converted to answer as this seemed to have helped you:

What do you expect to happen? Since the if statement changes refresh to false again, the label will only show very shortly. (In fact it will not show at all because of the layout event.)

You set refresh to true, then immediate set it to false again, so the label will never display. It needs to remain true for as long as you want the label visible. By the way, you can just use Event.current to get keyboard events; there’s no need to split this over two different functions. Keep everything in OnGUI.