While there are several question topics dealing with how to program GUIs in Unity, none of them really answer the question I wanted to know: How to lay out the actual code. After my first project in Unity, here are the thoughts I have on how to build a non-trivial GUI in Unity
Most of the Unity documentation offers up this paradigm
if( GUI.Button( pos, "Button" )) {
// handle button code here
}
This is bad for two reasons
- Encourages merging presentation and logic code
- Quickly gets unweildly for even a few buttons
Instead, create a series of button handler functions
// within OnGUI method
if( GUI.button( pos, "Button 1" )) { Button1_OnClick(); }
// later in class
private void Button1_OnClick() {
// handle button 1 click here
}
Yes, you should [always][4] use curly braces, even for a one line statement
This section might be more about general programming practice, but it happened in our team, so it's worth bringing up.
Don't try and put everything in the OnGUI event. Instead, split the code to draw controls up depending on what "screen" or "view" they're rendering, e.g.
private void renderMainMenu() {
// draw main menu
}
private boid renderOptionWindow() {
// draw options window
}
private boid renderCharacterSelection() {
// draw character selection
}
// etc...
Bad: What we did (tonnes of GameObject.Find) Good: Slots and signals.
Bad: Our half baked method Good: A central class, keeping track of the current "character" object, with a method to swap that out for a new prefab
Bad: Our scripts that are tightly coupled to certain objects Good: Generic scripts that can be applied to multiple objects.
Bad: attaching it to an empty game object Good: Unity's methods for this sort of thing.
[4]: TODO: get link for this