OnGui buttons/box leaves a copy or renders twice

I barely started working with Unity and a bug, or misunderstanding, that ive come across twice in the short time is some buttons being permanently being drawn on.

Its my understanding that buttons or boxes are not really objects in the game but are being drawn every frame(twice a frame for OnGui?). But somehow the first thing that I draw stays on the screen even if it doesn’t meet some conditionals.
Below is a truncated version of my onGui function any help/insight would be appreciated.

void OnGUI()
	{
		int count = mInventory.Count;
		if (GUI.Button (new Rect (10, 10, 150, 100), "erase")) {
			
			count = 0;
		}
		
		Debug.Log (count);
		for (int x = 0; x < count; x++) 
		{
			//Debug.Log(count);
			if (GUI.Button (new Rect (Screen.width / 2 + (100 * x), Screen.height / 2, 100, 20), "test")) 
			{
				
				
			}
			
		}
		
	}

Ive stripped much of my code away to show what I dont understand which is once I click on the erase button, my count should be zero and therefore the “test” buttons shouldnt be rendered but they are.

I have another example where I was displaying health on a guibox but “health 100” always stayed on top and i could see the health drop under that layer. I had a similar thing happen where i put a conditional : if(health < 50) → dont show anything, but still the health 100 stayed on top and the below layers went away as expected.

OnGUI() gets called multiple time per frame. GUI.Button() will only be true for a single frame, so on the next frame, count will again be set to ‘mInventory.Count’. So your code “hides” the ‘test’ button for a single frame…which won’t be noticeable.

To get a better understand of your code, replace the GUI.Button() call with GUI.RepeatButton(). GUI.RepeatButton() returns true as long as the button is held down. Or another way, for test purposes, replace line 6 with:

mInventory.Count = 0;