Forloop and GUI.Button Issues

Hello everyone, I’ve came to this issue when I trying to create a refresh button for searching files and each file has a button, the problem I’m experiencing is that it keeps calling the forloop which is ridiculously slowing down my game and is duplicating my buttons, here is the piece of code i’m using.

float yOffset = 0.0f;
		string [] MusicFiles = Directory.GetFiles(MusicLocation,"*.wav");
		DirectoryInfo dir = new DirectoryInfo(MusicLocation);
		FileInfo[] FilePaths = dir.GetFiles("*.*");
		
			
			//Debug.Log(MusicFiles[0]);
			for(int i = 0; i < MusicFiles.Length; i++)
			{
				if(Refresh)
				{
					if(GUI.Button(new Rect(2 ,yOffset,MusicSelectionWindow.width-2,20),MusicFiles*))*
  •  			{*
    

_ //GUI.Label(new Rect(100 ,yOffset,MusicSelectionWindow.width,20),MusicFiles*);_
_
}_
_
yOffset += 30;_
_ Debug.Log(MusicFiles);
Debug.Log(yOffset);
}
if(i == MusicFiles.Length)
{
Refresh = false;
//break;
}*_

* }*
Now with this piece of code is getting called from a function which is being used by OnGUI.
And I did have the refresh boolean outside of the for loop also and no matter what if the if statement is there the buttons never show up. Anyone have any suggestions that would be great, thanks.

OnGUI can be called multiple times per frame based on events (button presses, layout, etc.), so you’ll potentially see your loop execute multiple times. It’s an immediate mode GUI system, so you have to call the GUI functions each time OnGUI is called in order to display the GUI.

Your code for getting the file info should not be called from OnGUI, but should be moved outside. Your OnGUI code should then just loop through the values and render the buttons. I suspect this is what’s causing your slowdown.