Unity 3.x Game Development
by Example
Beginner's Guide
A seat-of-your-pants manual for building fun, groovy lile
games quickly with Unity 3.x
Ryan Henson Creighton
BIRMINGHAM - MUMBAI
Unity 3.x Game Development by Example
Beginner's Guide
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this informaon.
First edion: September 2010
Second edion: September 2011
Producon Reference: 1160911
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-184-0
www.packtpub.com
Cover Image by Dan Cox ( />Credits
Adventure, the game he authored with his ve-year-old daughter Cassie. Ryan maintains one
of the most acve and enjoyable blogs in the industry. He is also the author of the book that
you are currently reading.
When Ryan is not developing games, he's goong o with his two lile girls and his fun-
loving wife in downtown Toronto.
Big thanks to Cheryl, Cassandra, and Isabel for their love, their support,
and their cinnamon rolls. Thanks to Jean-Guy Niquet for introducing me to
Unity; to Jim "McMajorSupporter" McGinley for help with the book outline
and ongoing mentorship; to the technical reviewers and Packt sta for
leng me leave a few jokes in the book; and to David Barnes, for having
such a great sense of humor in the rst place. Special thanks to Michael
Garforth and friends from the #Unity3D IRC channel on Freenode. I also
want to thank Mom, God, and all the usual suspects.
About the Reviewer
Cliord Peters is currently a college student pursuing a degree in Computer Science. He
enjoys programming and has been doing so for the past 4 years. He enjoys using Unity and
hopes to use it more in the future.
Cliord has also helped to review the books Unity Game Development Essenals and Unity
3D Game Development Hotshot.
www.PacktPub.com
Support les, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at
www.PacktPub.com and as a print
book customer, you are entled to a discount on the eBook copy. Get in touch with us at
for more details.
At
www.PacktPub.com, you can also read a collecon of free technical arcles, sign up
Walk before you can run (or double jump) 17
There's no such thing as "nished" 18
Stop! Hammer me 18
Explore Bootcamp 19
The wonders of technology! 21
The Scene window 22
The Game window 22
The Hierarchy 23
The Project panel 24
The Inspector 25
Heads up? 26
Layers and layout dropdowns 28
Playback controls 28
Scene controls 29
Table of Contents
[ ii ]
Don't stop there—live a lile! 29
Summary 31
Big ambion, ny games 31
Chapter 2: Let's Start with the Sky 33
That lile lightbulb 34
The siren song of 3D 35
Features versus content 36
A game with no features 36
Mechanic versus skin 36
Trapped in your own skin 37
That singular piece of joy 37
One percent inspiraon 37
Motherload 38
Heads up! 40
Time for acon – Moving and rotang the light 69
Extra credit 72
Are you a luminary? 72
Who turned out the lights? 72
Darkness reigns 72
Time for acon – Camera mania 73
Time for acon – Test your game 73
Let's get physical 74
Time for acon – Adding physics to your game 74
Understanding the gravity of the situaon 75
More bounce to the ounce 76
Time for acon – Make the ball bouncy 76
Summary 79
Following the script 79
Chapter 4: Code Comfort 81
What is code? 81
Time for acon – Wring your rst Unity script 81
A leap of faith 83
Lick it and sck it 84
Disappear Me! 84
It's all Greek to me 84
You'll never go hungry again 85
With great sandwich comes great responsibility 86
Examining the code 86
Time for acon – Find the Mesh Renderer component 87
Time for acon – Make the ball re-appear 88
Ding! 89
Time for acon – Journey to the Unity Script Reference 89
The Renderer class 91
What's another word for "huh"? 94
Time for acon – Adding the sample code to your script 113
One nal tweak 115
What's a quaternion? 115
Wait, what's a quaternion? 115
WHAT THE HECK IS A QUATERNION?? 115
Educated guesses 116
More on Slerp 117
Right on target 117
Keep it up 119
Beyond the game mechanic 120
Chapter 5: Game #2: Robot Repair 121
You'll totally ip 122
A blank slate 123
You're making a scene 124
Time for acon – Seng up two scenes 124
No right answer 125
Time for acon – Preparing the GUI 126
The beat of your own drum 128
Time for acon – Creang and linking a custom GUI skin 128
Time for acon – Creang a buon UI control 130
Table of Contents
[ v ]
Want font? 134
Cover your assets 136
Time for acon – Nix the mip-mapping 137
Front and center 138
Time for acon – Centering the buon 138
To the game! 140
Time for acon – Adding both scenes to the Build List 141
Set the stage for robots 142
Pumpkin eater 179
Stabby McDragonpoker rides again 180
Table of Contents
[ vi ]
Game and match 180
Time for acon – ID the cards 180
Time for acon – Comparing the IDs 181
On to the nal boss 184
Endgame 184
Time for acon – Checking for victory 184
Endgame 187
Bring. It. On. 188
Chapter 7: Don't Be a Clock Blocker 193
Apply pressure 194
Time for acon – Preparing the clock script 194
Time for more acon – Preparing the clock text 195
Sll me for acon – Changing the clock text color 196
Time for acon rides again – Creang a font texture and material 197
Time for acon – What's with the ny font? 200
Time for acon – Preparing the clock code 201
Time for acon – Creang the countdown logic 202
Time for acon – Displaying the me onscreen 204
Picture it 207
Time for acon – Grabbing the picture clock graphics 207
Time for acon – Flexing those GUI muscles 209
The incredible shrinking clock 213
Keep your fork—there's pie! 214
How they did it 214
Time for acon – Rigging up the textures 216
Time for acon – Wring the pie chart script 217
Time for acon – Prefabulous 269
Time for acon – Lights, camera, apartment 272
Time for acon – Adding the character 273
Time for acon – Registering the animaons 274
Time for acon – Scripng the character 275
Time for acon – Opening the pod bay door, Hal 278
Time for acon – Collision-enable the character 278
Time for acon – Re-prefab the prefab 279
Time for acon – Apocalypse now? 280
Time for acon – Go boom 281
Time for acon – The point of impact 284
Time for acon – Hook up the explosion 285
Summary 286
Chapter 10: Game #3: The Break-Up Part 2 287
Time for acon – Amass some glass 287
Time for acon – Creang a Parcle System 288
Time for acon – Making it edgier! 291
Time for acon – Containing the explosion 292
Time for acon – Let's get lazy 293
Very variable? 296
Terminal velocity is a myth—bombs fall faster 296
Time for acon – Tagging the objects 297
Time for acon – Wring the collision detecon code 299
Time for acon – Animaon interrupts 300
Time for acon – Adding facial explosions 301
Time for acon – Making some noise 302
Time for acon – Adding sounds to the FallingObjectScript 303
What's the catch? 305
Time for acon – Mixing it up a bit 306
Summary 310
Time for acon – Animang the runner 367
Time for acon – How to "handle" Nurse Slipperfoot 369
Time for acon – You spin me right round 370
Time for acon – Deploying your game 373
Time to grow 375
Beyond the book 376
Table of Contents
[ ix ]
Appendix: References 377
Online resources 377
Oine resources 378
Free development tools 379
Graphics 379
Sound 379
Content sites 380
Game portals 380
Index 381
Preface
Beginner game developers are wonderfully opmisc, passionate, and ambious. But that
ambion is oen dangerous! Too oen, budding indie developers and hobbyists bite o
more than they can chew. Some of the most popular games in recent memory—Doodle
Jump, Angry Birds, and Canabalt, to name a few—have been fun, simple games that have
delighted players and delivered big prots to their creators. This is the perfect climate for
new game developers to succeed by creang simple games with Unity.
This book starts you o on the right foot, emphasizing small, simple game ideas and playable
projects that you can actually nish. The complexity of the games increases gradually as we
progress through the chapters. The chosen examples help you learn a wide variety of game
development techniques. With this understanding of Unity and bite-sized bits of programming,
you can make your own mark in the game industry by nishing fun, simple games.
Chapter 4, Code Comfort, connues the keep-up game project by gently introducing
scripng. Just by wring a few simple, thoroughly-explained lines of code, you can make
the paddle follow the mouse around the screen to add some interacvity to the game.
This chapter includes a crash course in game scripng that will renew your excitement for
programming where high school computer classes may have failed you.
Chapter 5, Game#2: Robot Repair, introduces an oen-overlooked aspect of game
development: "front-of-house" user interface design—the buons, logos, screens, dials,
bars, and sliders that sit in front of your game—is a complete discipline unto itself. Unity
3D includes a very meaty Graphical User Interface system that allows you to create controls
and ddly bits to usher your players through your game. We'll explore this system, and start
building a complete two-dimensional game with it! By the end of this chapter, you'll be
halfway to compleng Robot Repair, a colorful matching game with a twist.
Chapter 6, Game#2: Robot Repair Part 2, picks up where the last chapter le o. We'll add
interacvity to our GUI-based game, and add important tools to our game development tool
belt, including drawing random numbers and liming player control. When you're nished
with this chapter, you'll have a completely playable game using only the Unity GUI system,
and you'll have enough inial knowledge to explore the system yourself to create new
control schemes for your games.
Preface
[ 3 ]
Chapter 7, Don't be a Clock Blocker, is a standalone chapter that shows you how to build
three dierent game clocks: a number-based clock, a depleng bar clock, and a cool pie
wedge clock, all of which use the same underlying code. You can then add one of these
clocks to any of the game projects in this book, or reuse the code in a game of your own.
Chapter 8, Ticker Taker, revisits the keep-up game from earlier chapters and replaces the
simple primives with 3D models. You'll learn how to create materials and apply them to
models that you import from external art packages. You'll also learn how to detect collisions
between Game Objects, and how to print score results to the screen. By the end of this
chapter, you'll be well on your way to building Ticker Taker—a game where you bounce a
sll-beang human heart on a hospital dinner tray in a mad dash for the transplant ward!
Unity 3D (
A list of resources and links to
addional soware can be found in the appendix.
Who this book is for
If you've ever wanted to develop games, but have never felt "smart" enough to deal with
complex programming, this book is for you. It's also a great kick-start for developers coming
from other tools like Flash, Unreal Engine, and Game Maker Pro.
Conventions
In this book, you will nd several headings appearing frequently.
To give clear instrucons of how to complete a procedure or task, we use:
Time for action – heading
1. Acon 1
2. Acon 2
3. Acon 3
Instrucons oen need some extra explanaon so that they make sense, so they are
followed with:
What just happened?
This heading explains the working of tasks or instrucons that you have just completed.
You will also nd some other learning aids in the book, including:
Pop quiz – heading
These are short mulple choice quesons intended to help you test your own understanding.
Preface
[ 5 ]
Have a go hero – heading
These set praccal challenges and give you ideas for experimenng with what you have
learned.
You will also nd a number of styles of text that disnguish between dierent kinds of
informaon. Here are some examples of these styles, and an explanaon of their meaning.
Code words in text are shown as follows: "The result is that the rst me the
Update
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
Downloading the example code
You can download the example code les for all Packt books you have purchased from your
account at . If you purchased this book elsewhere, you can
visit and register to have the les e-mailed directly
to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you nd a mistake in one of our books—maybe a mistake in the text or the code—we
would be grateful if you would report this to us. By doing so, you can save other readers from
frustraon and help us improve subsequent versions of this book. If you nd any errata, please
report them by vising selecng your book, clicking
on the errata submission form link, and entering the details of your errata. Once your errata
are veried, your submission will be accepted and the errata will be uploaded on our website,
or added to any list of exisng errata, under the Errata secon of that tle. Any exisng errata
can be viewed by selecng your tle from />Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protecon of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the locaon
address or website name immediately so that we can pursue a remedy.
Please contact us at
with a link to the suspected
pirated material.
Preface
[ 7 ]
We appreciate your help in protecng our authors, and our ability to bring you
valuable content.
Questions
You can contact us at if you are having a problem with any