Skip to content

Instantly share code, notes, and snippets.

@charlieda
Created May 4, 2014 16:56
Show Gist options
  • Save charlieda/645ba780985a13ce123f to your computer and use it in GitHub Desktop.
Save charlieda/645ba780985a13ce123f to your computer and use it in GitHub Desktop.

My Experiences Coding in Unity

GUI

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

Handling Button Clicks

Most of the Unity documentation offers up this paradigm

if( GUI.Button( pos, "Button" )) {
  	// handle button code here
}

This is bad for two reasons

  1. Encourages merging presentation and logic code
  2. 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

Handling multiple screens

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...

Handling the large amounts of differnet components

Bad: What we did (tonnes of GameObject.Find) Good: Slots and signals.

Managing Spawning players

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

Scripts

Bad: Our scripts that are tightly coupled to certain objects Good: Generic scripts that can be applied to multiple objects.

Code not relevant to an objects

Bad: attaching it to an empty game object Good: Unity's methods for this sort of thing.

[4]: TODO: get link for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment