Unity 2D Tutorial: Reid Perkins-Buzo! DIG 4905 VG&S
Unity 2D Tutorial: Reid Perkins-Buzo! DIG 4905 VG&S
The only alternative was to use one of the various add-ons available on Unity’s Asset Store,
(e.g., 2D Toolkit or Orthello 2D Framework), any of which include great features but restricts
a game to work within its own set of constraints. And most of these were not cheap if you
wanted the full feature set.
While all of these options are still available, Unity 4.3 now has native tools that add a new
dimension to your workflow options: the 2nd dimension!
Note: This tutorial assumes you have at least some experience with Unity. You should know
the basics of working with Unity’s interface, GameObjects and Components, and you should
understand an instruction like, “Add a new droid to your scene by dragging droid from the
Project browser into the Hierarchy.”
If you think that sounds like C-3PO on a bad day, or if you’d like a moment to get yourself into
the right mindset for dragging droids, you may want to go through a tutorial that gives a
more basic introduction to Unity, such as this one.
Finally, note that the screen captures in this tutorial show the Unity OS X interface. However,
if you’re running on Windows don’t worry – since Unity works the same on Windows most of
these instructions will still work just fine. There will be a few minor differences (such as using
Windows Explorer instead of Finder) but you’ll get through it.
2) Game Resources
You’ll also need some art to make a 2D game. Fortunately, I made some Android images
for “droid vs apples”. They are in the same zip file as this tutorial in a folder called
“tutorial_resources“.
Page 1 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
The above-mentioned combo box is the first 2D-related feature you’ll come across in
Unity. It’s supposed to change the default import settings for your project’s art assets, but
so far I haven’t seen it work properly. Fortunately, this isn’t a problem because you can
change this setting in your project at any time, and doing so works fine.
This button toggles the Scene view’s camera between perspective and orthographic
projections. What’s the difference?
Page 2 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
The previous screenshot also shows how 2D mode hides the Scene Gizmo that lets you change
the orientation of the Scene view’s camera. With 2D mode enabled, the orientation is fixed so
the positive y-axis points up and the positive x-axis points to the right.
Important: Toggling this setting has no effect on how your game finally appears when played –
that’s determined by the camera(s) you set up in your scene – but it can be helpful when
arranging objects. You’ll probably move back and forth between these two modes while
creating your own 2D games, and even sometimes while creating 3D games, but this tutorial’s
screenshots all show the Scene view in 2D mode.
How easy is it to add a sprite to your scene using Unity’s new features? Try the following
experiment to find out.
Step 1: Drag rat.png from your Game Resources folder into the Scene view.
Step 2: Use some of the time you save making your game to send a thank you note to the
Unity devs.
That was pretty easy! If you got lost, just re-read those instructions and try again.
This demonstration was simplified by relying on Unity’s default import settings, which
oftentimes won’t be correct for your images. However, this serves to illustrate a point –
Unity’s new features make working in 2D amazingly easy! The rest of this tutorial covers
everything you’ll need to know to really get started working with
2D graphics in Unity.
5) Sprite Assets
It’s not obvious, but Unity created geometry for the object, too.
For each Sprite, Unity creates a mesh that basically fits the non-
clear pixels in your image. Notice the blue mesh in the following
image of the
Page 3 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
You can only assign one Sprite at a time, but later you’ll learn how
to update this field at runtime to create animations.
As you can see in the following image, the rat GameObject has a
Sprite named rat assigned to its renderer.
Be sure the Project browser is visible. Then click inside the Sprite
field in the Inspector to locate and highlight the Sprite asset in
the Project browser, as shown here:
As you can see in the previous screenshot, Unity highlighted an item named rat inside the
Project browser, which is a child of another object, also named cat. Two cats in the Project
browser? Yeah, that could be confusing. Here’s what’s going on:
• The parent rat is the Texture asset. It’s a reference to the original art file you
imported, cat.png, and controls the import settings used to create the Sprites from
your artwork. As you can see, it shows a nice thumbnail of the file’s contents.
• The child rat is a Sprite asset that Unity created when it imported rat.png. In this
case, there is only one child because Unity only created a single Sprite from the file,
but later in the section on slicing sprite sheets you’ll see how to create multiple
Sprites from a single image.
Note: Unity’s Sprite class actually only contains the information needed to access a
Texture2D object, which is what stores the real image data. You can create your own
Texture2D objects dynamically if you want to generate Sprites at runtime, but that requires
much more coding than we can concern ourselves with now.
As you saw with rat.png, you can add Sprites to your scene by dragging art assets from the
Finder directly into the Scene view (or the Hierarchy, if you’d like). But more commonly,
you’ll add assets to your project prior to adding objects to your scene.
Add to your project the remaining image files you downloaded: background_CB.png,
enemy_Apple.png, and kitkat_andy.png.
Page 4 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Unity gives you the following five options to get assets into your project:
1. Drag files from your Finder window into the Project browser.
2. Go to Assets > Import New Asset…, select your files and click Import.
3. Right-click within the Project browser, choose Assets > Import New Asset…, select your
files and click Import.
4. Within your OS, add the files directly to your project’s Assets directory, or one of its
subdirectories. Unity refreshes your project automatically to keep assets up to date.
Warning: Although it’s ok to add assets this way, you should never delete assets
directly from your file system. Instead, always delete assets from within Unity,
because Unity maintains metadata about your project’s assets and modifying the file
system directly could corrupt it.
5. Of course, you can also drag files directly into the Hierarchy or the Scene view, but
doing so has the additional effect of creating a GameObject in the current scene.
Add an enemy to your scene by dragging enemy_Apple from the Project browser to the
Hierarchy.
Page 5 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
We already imported kitkat_andy.png into the project, but the file is different from the
other ones. Instead of a single image, it contains several, as shown below:
Page 6 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Such a file is usually referred to as a sprite sheet, and you’ll want Unity to create a separate
Sprite asset for each of the sheet’s individual images.
Expand kitkat_andy in the Project browser. As we can see, Unity created a single child – a
Sprite containing the entire image.
Unity offers a simple way to treat this image as a sprite sheet. Select the top-level
kitkat_andy in the Project browser to open its Import Settings in the Inspector.
In this state, the kitkat_andy texture is unusable. If you tried to drag it into the Hierarchy,
you would get a message indicating it has no Sprites. That’s because you need to tell Unity
how you want to slice the sprite sheet.
With kitkat_andy selected in the Project browser, click Sprite Editor in the Inspector to
open the following window:
Page 7 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Unity’s automatic slicing works best when images are laid out with unambiguous empty space
between each item. Notice how Unity only finds the smiley face in the left image, but finds
three sprites in the image on the right.
The above images point out that you should arrange the images in your sprite sheets carefully.
Page 8 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Click on any of the sprites that Unity identified to edit the details of that sprite, including its
name, position, bounds, and pivot point.
You can make changes in the window’s fields, and you can adjust the bounds and pivot point
directly within the image.
Normally, after you’ve made changes, you would hit Apply or Revert in the upper right of the
Sprite Editor to save or discard them, respectively.
However, while the option to tweak Unity’s findings is great, we won’t need to do that here
because we aren’t going to use the sprites it found. The images in kitkat_andy.png are
arranged in four equally sized rectangles, and Unity has a separate option to handle cases like
this one.
Page 9 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
You can still select individual cells in the grid and tweak their settings like you could when
using Unity’s Automatic slicing option, but that’s unnecessary for these sprites.
Click Apply in the upper-right of the Sprite Editor to commit your changes. Notice how Unity
updates the Project browser so that the top-level kitkat_andy texture asset now contains
four child Sprites, named kitkat_andy_0, kitkat_andy_1, and so on, as shown below:
Create a new empty GameObject by choosing GameObject > CreateEmpty. Click on the
GameObject in the Hierarchy browser and rename the object andy, and set its Position to
(-2, 0, 0) in the Inspector.
Page 10 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
With andy selected in the
Hierarchy, add a Sprite
Renderer component by
clicking Add Component
in the Inspector. See the
left image.
Click the small circle/target icon on the right of the Sprite Renderer‘s Sprite field to open
the Select Sprite dialog. The icon is shown below:
The dialog that appears contains two tabs, Assets and Scene. These show you all the Sprites
you have in your project and in the current scene, respectively.
Choose the Assets tab and then click on kitkat_andy_0 to assign that Sprite to the renderer.
Page 11 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
We now have all the Sprites in the game, we can configure how the game should look for the
players. First, we are designing this game for an Android system, so we will set our Game
view size to 960 × 540 pixels, which is a standard screen size for many Android devices.
Page 12 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
It may not look exactly like this, because Unity resizes the Game view to maintain your
chosen aspect ratio within the available space. Regardless of its scale, you should see the
same amount of the scene in your view.
Obviously, that isn’t quite right. You’re seeing the results of three different problems here,
and you’ll correct each one in turn:
• The scene’s camera is not set up properly, so the background doesn’t fill the view
properly.
• The scene is rendering your game objects in the wrong order, so the rat and Apple are
both behind the background.
• The image quality is not very good. This one might be hard to detect with the current
camera settings. But trust me, it can be better!
Page 13 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Not much different from the perspective projection! In 3 dimensional games, sprites change
size based on their distance from the camera. In 2D games, how do you zoom in so that the
background fills the screen? You could try scaling your GameObjects, but using the camera’s
Size property is the more
robust approach.
Page 14 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
When we imported our Sprites into Unity we simply accepted the default import settings for
them. Many times this is a good choice, but it never hurts to review them, especially when
you are using Sprite Sheets or larger textures for the background. Sometimes Unity’s
“one size fits all” approach doesn’t work in these
cases. Having inappropriate import settings for your
sprite images is the most common cause of a weaker
appearance for a game.
Also note that the format is set to Compressed. Clicking on the drop-down menu shows three
settings: Compressed, 16-bit and TrueColor. These correspond to 8-bit, 16-bit and 32-bit
per pixel formats, respectively. The more bits per pixel, the higher the quality, but also the
greater the memory required and the more processing power it takes to render the sprite. So
it’s a trade-off.
Page 15 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
For our purposes, the background_CB sprite has little detail, so the Compressed setting is
best. For an image with a plethora of detail or great significance in the game, use a less
compressed setting.
Checking the import settings for the rest of our sprites, we can see that since all of them are
small compared to the default Max Size, we can leave that alone. None of them have much
significant detail, so leave them at Compressed for the format.
Unity has an order in which it tells the sprites to be drawn in the graphics buffer. This is
called the Draw Order and it ensures that sprites meant to be in front of other sprites, end
up there. We saw that both Starling and Cocos2D have a way of handling this as well. It is a
common task for any game engine. Generally, in a 2D game, sprites are stacked in the draw
order as they are introduced or given a z-index as they are added to the game play. This z-
index number provides the Draw Order for many game development environments.
Select the rat in the Hierarchy and in the Inspector, set its Position property z-coordinate
to 2. It disappears behind the background_CB sprite. Select enemy_Apple in the Hierarchy
and set its z-coordinate to 3. It also disappears behind the background_CB sprite. So
adjusting the z-coordinate would provide a simple way of controlling the draw order.
Although we can use this approach in Unity, it also has a unique feature called a Sorting
Layer which provides some additional flexibility for managing the draw order.
Click + in the
Sorting Layers group to create a new sorting layer and
name it Rats. Do that two more times to create a sorting
layer named Apples and one named Andy. Your editor
should now look like the image on the left.
Page 16 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
These layers define the draw order – Layer 0, named Default, is the furthest in the back, with
Layer 1, named Rats, in front of it, and so on.
Right now, each of the GameObjects you’ve added is using the Default Sorting Layer. For
the background sprite, that’s fine because you want it in the back anyway, but you need to
change the Sorting Layer for the other sprites.
Select rat in the Hierarchy and set its Sorting Layer to Rats. You’ll immediately notice that
the rat is now visible in both the Scene and Game views.
Select enemy_Apple in the Hierarchy and set its Sorting Layer to Apples. Finally, select
andy in the Hierarchy and set its Sorting Layer to Andy to ensure your player renders on top
of all the other sprites. Your Game view now looks like this:
Page 17 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Uncheck the Apply Root Motion (this doesn’t apply to our type of Sprites). If we were using
gravity or other physical forces in our game, we would check the Animate Physics box.
Change to
4 samples
per second Start of the timeline
You can see the timeline in the Animation window. It is divided into samples which
correspond to frames in the Sprite animation.
Now select andy in the Hierarchy browser. It is crucial that the appropriate Game Object be
selected in the Hierarchy before we do the next step. Otherwise no animation will be
attached to the Game Object (in this case andy). Click to create a new clip as in the image:
A new window appears titled Create New Animation. Call it andy_walks and click Save. It
will be saved in the Assets folder of our project folder by default. If we were going to have
many animations we should create a new folder inside of the Assets folder and save them all
in it for the sake of being organized.
Page 18 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
Now drag all the selected Sprite images up to the start of the
timeline in the Animation window as in the image to the
left.
The animation is
attached to andy in the
Hierarchy browser
Switch to the Game tab in the viewer and click on the red play button. We should now see
andy going through a walk cycle in the Game viewer tab.
Page 19 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
We need to be able to “spawn” rat and enemy_Apple sprites through code as we need them.
In order to do that we need to turn the Game Object sprites rat and enemy_Apple in the
Hierarchy into what Unity calls Prefabs. A Prefab is a Game Object that is pre-loaded with
all the components it needs to run in the game, but is kept in the Project browser until it is
needed. Then it will be created in the Hierarchy by a game script.
First right click in the Project browser and select Create > Folder. Name the folder Prefabs.
From the Hierarchy browser, drag the the enemy_Apple and the rat into the Prefabs folder.
Check to see if they are in the folder, and if they have been successful placed into the
Prefabs folder, delete the enemy_Apple and the rat from the Hierarchy browser (right-click
on each one in the Hierarchy browser, then choose Delete.
These Prefabs should not be confused with the images of the rat and enemy_Apple in the
images folder. The Prefabs are Game Objects pre-loaded with all the components for the
game, whereas the images are only Unity’s stored image.
Page 20 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
We are now in a position to write the scripts for the game. However, writing detailed
instructions on coding C# would take another 20 pages, and is really beyond the scope of this
introductory tutorial. All of the scripts are included in the completed version of the game
(which is part of the zip archive which includes this tutorial). The have extensive comments in
them explaing the sections of the code. If you would like to gain a more complete
understanding of the mechanics of the game’s code, please examine the comments in
those scripts.
As in the Starling and Cocos2D tutorials, we are using the notion of a finite state machine to
guide the development of this game. With that in mind, we need to add two more states to
the game, a GameStart scene and a GameOver scene. This will give us a complete finite
state machine of three states: Start, Main, and Over.
To create new scene in Unity, simply select File > New Scene. It may then be fashioned into
either the Start or Over state. The finished game has the three scenes for our finite state
machine already built. Take a look at them to see how they were done.
The last step is to build the app for an Android device. We do this in the
Build Settings Panel.
Go File > Build Settings … to open this panel in a floating window. First,
select Android from the Platform list in the lower left. Next, since we
are just trying out the game, click the Development Build check box.
Leave everything else as is for now.
We now need to add the scenes we wish to include in the build into the
upper Scenes in Build area of the panel. In the completed version of the
game, we have three scenes we wish to include:
Start, Main, and Over.
Page 21 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
The Icon section should open by default. Click the Select text for each icon size and load the
android-kitkat-full image for each of the icons. Unity will take care of generating all the
required Android icons as long as you set this up correctly.
Next select the Other Settings. Set the Bundle Identifier to a reverse URL identifier like so:
com.mycompany.product_name
Set the Bundle Version to the version number you’ve need. In our case leave it at 1.0. Set
the Minimum API Level to the appropriate level for the app. Generally the lower you can set
it the better, since then it will work on a broader range of Android devices. However the
more complex a game becomes, and the more it relies on advanced graphics features like
particle effects, the less likely it will run on a low end device. Leave everything else at the
default settings.
Now click the Publishing Settings. This where you set up the keystore which Google Play
requires to distribute a game. The keystore locks the app cryptographically which secures it
against others hacking the app. The Android documentation states:
The Android system requires that all installed applications be digitally signed with a
certificate whose private key is held by the application's developer. The Android system
uses the certificate as a means of identifying the author of an application and establishing
trust relationships between applications. The certificate is not used to control which
applications the user can install. The certificate does not need to be signed by a
certificate authority: it is perfectly allowable, and typical, for Android applications to use
self-signed certificates. http://developer.android.com/tools/publishing/app-signing.html
If this is the first time building this app, check the Create New Keystore checkbox.
Otherwise click Browse Keystore to find he keystore you already created. In the Keystore
Password text box, type a password you wish to use, the confirm the same password in the
Confirm Password text box.
Just below the password text boxes is an area to specify the Key alias for our app. Since we
are doing a Development Build, we can leave the Key alias at unsigned.
Page 22 of 23
Reid Perkins-Buzo! DIG 4905 VG&S
On my set-up it takes about 45 to 60 seconds to complete the build, push the APK file to the
Android device and start it running.
Page 23 of 23