- Home /
Question by
Jan_Julius · Oct 28, 2014 at 11:26 AM ·
onguilevelsgui.button
Is there a way to shorten this code or make it more compact?
I'm making levels and a level select, what can I do here to make it shorter or atleast more readable considering there are a lot more.
if(GUI.Button (new Rect(100, 100, 300, 75), "Level 1", interStyle)){
newLevel (1);
}
if(PlayerPrefs.GetInt("LevelC1") == 1){
if(GUI.Button (new Rect(100, 175, 300, 75), "Level 2", interStyle)){
newLevel (2);
}
} else { GUI.Label(new Rect(100, 175, 300, 75), "Level Locked", interStyle); }
if(PlayerPrefs.GetInt("LevelC2") == 1){
if(GUI.Button (new Rect(100, 250, 300, 75), "Level 3", interStyle)){
newLevel (3);
}
} else { GUI.Label(new Rect(100, 250, 300, 75), "Level Locked", interStyle); }
if(PlayerPrefs.GetInt("LevelC3") == 1){
if(GUI.Button (new Rect(100, 325, 300, 75), "Level 4", interStyle)){
}
} else { GUI.Label(new Rect(100, 325, 300, 75), "Level Locked", interStyle); }
if(PlayerPrefs.GetInt("LevelC4") == 1){
if(GUI.Button (new Rect(100, 400, 300, 75), "Level 5", interStyle)){
}
} else { GUI.Label(new Rect(100, 400, 300, 75), "Level Locked", interStyle); }
Thanks,
Jan Julius.
Comment
Best Answer
Answer by HarshadK · Oct 28, 2014 at 11:52 AM
You can use a for loop as below:
void OnGUI()
{
for (int i=0; i<4; i++)
{
if(i==0)
{
if(GUI.Button (new Rect(100, 100, 300, 75), "Level "+i.ToString()))
{
newLevel (i);
}
}
else
{
if(PlayerPrefs.GetInt("LevelC"+i.ToString()) == 1)
{
if(GUI.Button (new Rect(100, 100+(i*75), 300, 75), "Level "+(i+1).ToString())){
newLevel (i+1);
}
}
else
{
GUI.Label(new Rect(100, 100+(i*75), 300, 75), "Level Locked");
}
}
}
}
Wow, excuse me for even asking this question, I couldn't figure out in my brain to use that newLevel(i) I thought it was impossible, maybe I should take some rest lol.
Thanks a lot regardless. :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613170142im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
OnGUI() works on Editor but not on Android Device 0 Answers
mouse over and change texture 0 Answers
gui content dynamic change with screen size 1 Answer
How to use if(GUI.Button with Flash? 1 Answer