- Home /
Is this code enough to crash Unity?
Okay, so what I'm trying to do with the below code is generate a 4x4 grid of colored buttons that is generated from an array. I don't think I can use the SelectionGrid function for this case, because I can't change the color of the buttons. (It's a window function so it's called from the GUI function.) However, when I run the code, it crashes Unity. Why is this?
void SavedColorsPanel (int windowID) {
int i = 0;
Color curGuiColor = GUI.backgroundColor;
for(int x = 0;x<4;x++) {
for(int y = 0;y<4;x++) {
if(i<sceneColors.Count) {
GUI.backgroundColor = sceneColors[i];
GUI.Button(new Rect( y*20+10, x*20+10, 25, 20), "");
i++;
} else {
GUI.backgroundColor = Color.white;
GUI.Button(new Rect( y*20+10, x*20+10, 25, 20), "");
}
}
}
GUI.backgroundColor = curGuiColor;
GUI.DragWindow();
}
You're incrementing x in both the inner and the outer loop. I'm guessing that wasn't intentional. :)
Answer by jahroy · Dec 11, 2011 at 10:04 PM
Yes, that code will halt any computer that runs it .
You never change the value of y, so it remains at zero (which is less than 4).
Your for loop will execute forever.
This is an example of an infinite loop.
;) typical copy&paste error :D. That's why a lot programmer i know always type in each line. I use copy&paste a lot since i'm not that fast at writing, but i always keep in $$anonymous$$d to check what i've pasted together :D
If you use Visual Studio, the editor has nifty little utilities that help you spawn standard code templates so you don't have to copy-paste code. $$anonymous$$icrosoft uses the term "Code Snippet" for them:
http://msdn.microsoft.com/en-us/library/ms165399.aspx
For example, you can write "for" and then hit TAB twice, and it'll spawn a complete for-loop, and if you change the iterator declaration, it updates the iterator reference in the other two references (the stop-condition and the increment) automatically. It's great for stuff like this, where you want an inner for-loop's iterator to be called something else than the outer for-loop's. :)
Code snippets include all common patterns (eg. while, if-else, foreach, switch, etc), and you can create custom snippets too.