2D Game Prototyping in Unity3D Using the GUI Class

Using the GUI class is probably the simplest way to create 2D game prototypes in Unity3D.

To draw an image to the screen, you only need a single line of code; no objects need to be instantiated whatsoever:


For this to work, this line needs to be in the OnGUI method, and a file named bunny has to exist in the Assets/Resources folder (the actual file would be named bunny.png, bunny.psd, or whatever your favorite file format is).

For many uses, this is fast enough.

When you’re drawing many images every frame, there’s some room for optimization:

  • The OnGUI method is called multiple times per frame (once for each input event, and once for the rendering). As we’re only drawing a texture here, it’s enough to draw the texture only when rendering.
  • Also, Resources.Load is called each time. This doesn’t mean our bunny is loaded from disk all the time; instead, it’s only loaded the first time, and loaded from cache every subsequent time. Still, the cached data is retrieved every time by string – a relatively slow operation.

So in case the GUI code is getting slow, you could try the following:

// in your class declaration
Texture2D bunny;

// in Start()
 bunny = (Texture2D)Resources.Load("bunny");

// in OnGUI()
if (Event.current.type == EventType.Repaint)

Using the GUI class has a major drawback on iOS and Android: each image or text string is sent separately to the GPU, resulting in many draw calls. As these are really slow operations on mobile platforms, this is a real performance killer.

An other drawback is that you won’t be able to use the built-in physics engine. Depending on what you want to prototype, this may be an issue.

In the next post, I’ll discuss how sprite manager systems, such as GUISpriteUI, can be used to get faster 2D graphics on mobile platforms.

2 thoughts on “2D Game Prototyping in Unity3D Using the GUI Class”

  1. How do you instantiate the bunny graphic one or more times into your 2d scene?

  2. One way to do this is to create a Bunny class with an OnGUI method (not deriving from Monobehaviour).
    In your main game class’ OnGUI method, you would then loop over the bunnies and call their OnGUI methods.

    Having to call these methods manually may seem silly, but for 2D games implemented this way, you’ll be happy to be able to control the order of the calls manually.

Leave a comment

Your email address will not be published. Required fields are marked *