Which code is more efficient?

Hi, I’m new to unity and I’m not sure about the best way to do certain things. What I’ve got is a title screen that lets the player choose a level from a list. The levels can only be selected after they’ve been unlocked, which can be done by completing the level before it. I’ve got two different working versions of the list, but I’m wondering which would use less resources. I’d also like to note that I will be expanding the list later on, so if it could have an effect with more levels, that should be taken into consideration.

First set of code - for loop:

//Goes through level count - 1(title screen), adds buttons to screen,
//and checks to see if the button is clicked
for(int i=0;i<(Application.levelCount-1);i++)
{
	if(levelUnlocks[i])
	{
		if(GUI.Button(new Rect((Screen.width/2)-40,(Screen.height/2)+(30*(i-1)),80,20), "Level "+(i+1).ToString()))
		{
			Application.LoadLevel(i+1);
		}
	}
}

Second set of code - individual button code:

//Level 1 button
if(GUI.Button(new Rect((Screen.width/2)-40,(Screen.height/2)-30,80,20), "Level 1"))
{
	Application.LoadLevel(1);
}

//Level 2 button
if(levelUnlock2)
{
	if(GUI.Button(new Rect((Screen.width/2)-40,(Screen.height/2)+0,80,20), "Level 2"))
	{
		Application.LoadLevel(2);
	}
}

//Level 3 button
if(levelUnlock3)
{
	if(GUI.Button(new Rect((Screen.width/2)-40,(Screen.height/2)+30,80,20), "Level 3"))
	{
		Application.LoadLevel(3);
	}
}

Variables:

//First set of code variable
public static bool[] levelUnlocks = {true,false,false};
//Second set of code variables
public static bool levelUnlock2 = false;
public static bool levelUnlock3 = false;

There isn’t really a great deal in it tbh.

The only thing which I would consider changing would be your button positions (for cleanness):

Rect position = new Rect((Screen.width/2)-40,(Screen.height/2)-30,80,20);
for(int i=0;i<(Application.levelCount-1);i++)
{
    if(levelUnlocks[i])
    {
        if(GUI.Button(position , "Level "+(i+1).ToString()))
        {
            Application.LoadLevel(i+1);
        }
        position.y += 30;
    }
}

Thanks! I wasn’t really sure so I asked. Thanks for the clean code as well. I’ll definitely use it.

Write code that works and is easily maintainable. Worry about micro-optimizations later (or not at all…). I believe it should be fairly clear that using a loop is far easier to work with and maintain compared to repeatedly copy-pasted code.

–Eric