Home Game Development Unity 4.x Game Development by Example: Beginner's Guide - Third Edition

Unity 4.x Game Development by Example: Beginner's Guide - Third Edition

By Ryan Henson Creighton
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99 $28.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99 $28.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    That's One Fancy Hammer!
About this book
Unity is one of the biggest game engines in the world, providing the user with a range of important tools that they need to bring their ideas into reality. Beginner game developers are optimistic, passionate, and ambitious, but that ambition can be dangerous! Too often, budding indie developers and hobbyists bite off more than they can chew. Games like Angry Birds, Cut the Rope, and Fruit Ninja are fun, simple games that have delighted players and delivered big profits to their creators. This is the perfect climate for new game developers to succeed by creating simple games with Unity, starting today. This book teaches you the ins and outs of the unique Unity game engine interface. Clear and concise code examples written in both Unity Javascript and C# take you through the step-by-step process of building five small, functional games. With this understanding you can start making your own mark on the game industry! With absolutely no programming or game development experience, you will learn how to build five simple games in Unity by following step-by-step instructions, peppered with amusing analogies and anecdotes from an experienced indie developer. Following a primer on simplifying your game ideas to that single “something” that keeps players coming back for more, dive into the Unity game engine by creating a simple bat-and-ball game. From there, you'll build a complete memory game using only the Unity GUI system. After building a 2.5D mouse avoider game, you'll learn how to re-skin the project to completely change the game's theme. Incorporating everything you've learned, you'll return to complete the bat-and-ball game by adding scoring, replay flow, sound effects, and animations. Finally, in the new bonus chapter, you'll program some simple AI (Artificial Intelligence) for a tic tac toe game. "Unity 4.x Game Development by Example" is a fun and light-hearted exploration of one of the most powerful game engines on the market today. Find out what all the fuss is about by getting up to speed using this book!
Publication date:
December 2013
Publisher
Packt
Pages
572
ISBN
9781849695268

 

Chapter 1. That's One Fancy Hammer!

Technology is a tool. It helps us accomplish amazing things, hopefully more quickly, more easily, and more amazingly than if we hadn't used the tool. Before we had newfangled steam-powered hammering machines, we had hammers. And before we had hammers, we had the painful process of smacking a nail into a board with our bare hands. Technology is all about making our lives better and easier. And less painful.

 

Introducing Unity 3D


Unity 3D is a piece of technology that strives to make life better and easier for game developers. Unity is a game engine, and a game authoring tool, which enables creative folks like you to build video games.

By using Unity, you can build video games more quickly and easily than ever before. In the past, building games required an enormous stack of punch cards, a computer that filled a whole room, and a burnt sacrificial offering to an ancient god named Fortran. Today, instead of spanking nails into boards with your palm, you have Unity. Consider it your hammer—a new piece of technology for your creative tool belt.

 

The engine, the tool, and the all-weather tires


You may have heard people call Unity and other tools "game engines". That's almost correct. The confusion here comes from the fact that we have three distinct things, and we call them all "Unity".

When you download Unity, as you'll do in a moment, you're downloading the Unity 3D game authoring tool. To use a car analogy, the authoring tool works like your auto body shop. You use it to design and build the car's chassis, its handling, and its sweet, sweet leather interior and boss rims.

Under the hood, the authoring tool uses the Unity game engine, which is like the driving force behind your game. Unless you work out a pricy licensing deal with Unity Technologies, you are not allowed to mess around with the engine itself, but the engine is the piece that makes your car run.

When you're finished designing your game with the Unity authoring tool, your content gets bundled with the Unity game engine, and the two of them are packaged together with an extra piece that enables the game to run in a certain situation. The analogy gets weaker here, but consider tires: you can add snow tires to your car so that it can drive in the tundra, or dune buggy tires so that it can drive in the desert. In this way, you package your game content with a certain target platform in mind: PC, Mac, iOS, Android, or one of the various home video game consoles.

 

Unity takes over the world


Throughout this book, we'll be distilling our game development dreams down to small, bite-sized nuggets instead of launching into any sweepingly epic open-world game. The idea here is to focus on something you can actually finish instead of getting bogged down in an impossibly ambitious opus. This book will teach you how to build five games, each of which focuses on a small, simple gameplay mechanic. You'll learn how to build discrete pieces of functionality that you can apply to each project, filling the games out to make them complete experiences. When you're finished, you can publish these games on the web, Mac, PC, and Linux systems. If you spring for an additional software license for one of Unity's many add-ons, you may be able to publish your games for other platforms, including home video game consoles.

The team behind Unity 3D is constantly working on packages and export options ("snow tires") for other platforms. At the time of this writing, Unity could additionally create games that can be played on iOS, Android devices, Xbox One, PS4, and Wii U. Each of these tools is an add-on functionality to the core Unity package, and comes with an additional cost, while console development usually requires a developer relationship with the platform owner. These licenses are constantly in flux, however, and the mobile development add-ons that used to cost an additional fee are now free. By the time you read this book, who knows? To be safe, we'll stick to the core Unity 3D program for the remainder of this book.

With the initial skills that you learn in this book, you'll be able to expand on your knowledge to start building more and more complex projects. The key is to start with something you can finish, and then for each new project that you build, to add small pieces of functionality that challenge you and expand your knowledge. Any successful plan for world domination begins by drawing a territorial border in your backyard; consider this book as your backyard.

 

Why choose Unity?


There are a great many game authoring tools, engines, and frameworks that you may have explored or read about before investigating Unity 3D. What makes Unity an attractive option? Here are a few selling points:

  • Large community: You want to avoid going with a tool that only you and some middle-schooler in Siberia know how to operate. Unity has a very large user base, which makes it much quicker and easier to find answers to your questions, and to find online videos, tutorials and books like this one that explain new concepts. A large community also implies that development on the software will continue. Nothing's worse than training on a tool that is later abandoned.

  • Social proof: The fact that large companies have bought into or partnered with Unity Technologies bodes very well. Electronic Arts has purchased a site-wide license, and (at the time of this writing) two out of three major console manufacturers have struck licensing deals with Unity to spur development on their systems.

  • Bang for the buck: If you ever "go pro", you'll want to invest some pennies against a full version of Unity. While it's not chicken scratch, the amount of power and the number of options you get from Unity vastly outweigh the cost outlay.

  • Market success: On any given day, a survey of the chart-topping iOS games turns up a proportionately large number of Unity-developed titles. Unity is being used by a great many developers to create games that survive in the market, and thrive once they're there.

  • Customizability: The entire Unity authoring tool can, itself, be authored. Developers can create their own windows, buttons, and panels to add to the Unity authoring tool, which has led to a very active secondary market called the Unity Asset Store, where you can download toolmakers' creations to make your development experience even better.

  • Multiplatform: It mystifies me why people pour so much energy into tools like XCode, which can target exactly one platform (or maybe two? I honestly don't care enough to check). When faced with such a diverse marketplace, it's a savvy developer who chooses a technology that targets multiple platforms.

 

Why burn this book and run away screaming?


Of course, no game development tool is perfect, and in certain areas, other tools have the advantage over Unity. Here are a few places where Unity doesn't stack up against its rivals:

  • Learning Curve: Even with the abundance of training available, Unity largely requires developers to learn how to program and to deal with complex concepts such as shaders and the third dimension. If you've come to Unity after hearing "it makes game development simple! Anyone can do it!", you've been fed a hot bowl full of filthy lies.

  • Cost: Bang for buck notwithstanding, when you get into a situation where you're buying pro versions of Unity for an entire development team, and the Unity Asset Server on top of that, as well as copies of the deployment add-ons, the cost begins to add up. I may have knocked XCode in the previous section, but it does have the advantage of being free.

  • Purity: If you're coming from a "pure" programming background, some of the ways in which you solve different problems in Unity may seem outright sacrilegious to you. If the thought of working within a GUI and dragging things on top of other things to create reflexive relationships gives you the willies, you may not dig the way Unity gets things done.

 

Browser-based 3D – welcome to the future


One of Unity's most astonishing capabilities is that it can deliver a full 3D game experience right inside your web browser. It does this with the Unity Web Player—a free browser plugin that embeds and runs Unity content on the web.

 

Time for action – install the Unity Web Player


Before you dive into the world of Unity games, download the Unity Web Player. Much the same way the Flash player runs Flash-created content, the Unity Web Player is a plugin that runs Unity-created content in your web browser.

  1. Go to http://unity3d.com/webplayer (click either the Windows or Mac OS X button on the page to select your platform).

  2. Click on Download.

  3. Follow all of the onscreen prompts until the Web Player has finished installing.

  4. The install process is only slightly more involved on a Mac. You have to download and run a .dmg file, and then enter your administrator password to install the plugin, but it's relatively quick and painless.

 

Welcome to Unity 3D!


Now that you've installed the Web Player, you can view the content created with the Unity 3D authoring tool in your browser.

 

What can I build with Unity?


In order to fully appreciate how fancy this new hammer is, let's take a look at some projects that other people have created with Unity. While these games may be completely out of our reach at the moment, let's find out how game developers have pushed this amazing tool to its very limits.

FusionFall

The first stop on our whirlwind Unity tour is FusionFall—a Massively Multiplayer Online Role-Playing Game (MMORPG). You can find it at fusionfall.com.

FusionFall was commissioned by the Cartoon Network teevee franchise, and takes place in a re-imagined, anime-style world where popular Cartoon Network characters are all grown up. Darker, more sophisticated versions of The Powerpuff Girls, Dexter's Laboratory, Foster's Home for Imaginary Friends, and the kids from Codename: Kids Next Door run around battling a slimy green alien menace.

 

Completely hammered


While it's not the newest game on our tour, FusionFall remains one of the largest, most expensive and technically complex Unity games around. FusionFall is historically important to Unity Technologies, as it helped draw a lot of attention to the then-unknown Unity game engine when the game was released. As a tech demo, it's one of the very best showcases of what your new technological hammer can really do! FusionFall has real-time multiplayer networking, chat, quests, combat, inventory, NPCs (non-player characters), basic AI (artificial intelligence), name generation, avatar creation and costumes. And that's just a highlight of the game's feature set. This game packs a lot of depth.

 

Should we try to build FusionFall?


At this point, you might be thinking to yourself, "Heck YES! FusionFall is exactly the kind of game I want to create with Unity, and this book is going to show me how!"

Unfortunately, a step-by-step guide to creating a game the size and scope of FusionFall would likely require its own flatbed truck to transport, and you'd need a few friends to help you turn each enormous page. It would take you the rest of your life to read, and on your deathbed, you'd finally realize the grave error that you had made in ordering it online in the first place, despite having qualified for free shipping.

Here's why: the FusionFall credits

http://fusionfall.cartoonnetwork.com/game/credits.php

This page lists all of the people involved in bringing the game to life. Cartoon Network enlisted the help of an experienced Korean MMO developer called Grigon Entertainment. There are over 80 names on that credits list! Clearly, only two courses of action are available to you:

  1. Build a cloning machine and make 79 copies of yourself. Send each of those copies to school to study various disciplines, including marketing, server programming, and 3D animation. Then spend a year building the game with your clones. Keep track of who's who by using a sophisticated armband system.

  2. Give up now because you'll never make the game of your dreams.

 

Another option


Before you do something rash and abandon game development for farming, let's take another look at this. FusionFall is very impressive, and it might look a lot like the game that you've always dreamed of making. This book is not about crushing your dreams. It's about dialing down your expectations, putting those dreams in an airtight jar, and taking baby steps. Confucius said:

"A journey of a thousand miles begins with a single step."

I don't know much about the man's hobbies, but if he was into video games, he might have said something similar about them—creating a game with a thousand awesome features begins by creating a single, less feature-rich game.

So, let's put the FusionFall dream in an airtight jar and come back to it when we're ready. We'll take a look at some smaller Unity 3D game examples and talk about what it took to build them.

Off-Road Velociraptor Safari

No tour of Unity 3D games would be complete without a trip to Blurst.com—the game portal owned and operated by independent game developer Flashbang Studios. In addition to hosting games by other independent game developers, Flashbang has packed Blurst with its own slate of kooky content, including Off-Road Velociraptor Safari:

In Off-Road Velociraptor Safari, you play with a dinosaur in a pith helmet and a monocle driving a jeep equipped with a deadly spiked ball on a chain (just like in the archaeology textbooks). Your goal is to spin around in your jeep doing tricks and murdering your fellow dinosaurs (obviously).

For many independent game developers and reviewers, Off-Road Velociraptor Safari was their first introduction to Unity. Some reviewers said that they were stunned that a fully 3D game could play in the browser. Other reviewers were a little bummed that the game was sluggish on slower computers. We'll talk about optimization a little later, but it's not too early to keep performance in mind as you start out.

Fewer features, more promises

If you play Off-Road Velociraptor Safari and some of the other games on the Blurst site, you'll get a better sense of what you can do with Unity without a team of experienced Korean MMO developers. The game has 3D models, physics (code that controls how things move around somewhat realistically), collisions (code that detects when things hit each other), music, and sound effects. Just like FusionFall, the game can be played in the browser with the Unity Web Player plugin. Flashbang Studios also sells downloadable versions of its games, demonstrating that Unity can produce standalone executable game files too.

Maybe we should build Off-Road Velociraptor Safari?

Right then! We can't create FusionFall just yet, but we can surely create a tiny game like Off-Road Velociraptor Safari, right? Well... no. Again, this book isn't about crushing your game development dreams. But the fact remains that Off-Road Velociraptor Safari took five supremely talented and experienced guys eight weeks to build on full-time hours, and they've been tweaking and improving it ever since. Even a game like this, which may seem quite small in comparison to full-blown MMO like FusionFall, is a daunting challenge for a solo developer. Put it in a jar up on the shelf, and let's take a look at something you'll have more success with.

 

I bent my Wooglie


Wooglie.com is a Unity game portal hosted by M2H Game Studio in the Netherlands. One glance at the front page will tell you that it's a far different portal than Blurst.com. Many of the Wooglie games are rough around the edges, and lack the sophistication and slick professional sheen of the games on Blurst. But here is where we'll make our start with Unity. This is exactly where you need to begin as a new game developer, or as someone approaching a new piece of technology like Unity.

Play through a selection of games on Wooglie. I'll highlight a few of them for your interest:

Big Fun Racing

Big Fun Racing is a simple but effective game where you zip around collecting coins in a toy truck. It features a number of different levels and unlockable vehicles. The game designer sunk a few months into the game in his off-hours, with a little help from outsource artists to create the vehicle models.

Diceworks

Diceworks is a very simple, well-polished game designed in Unity 3D for iPhones. We won't be covering any iPhone development, but it's good to know that your Unity content can be deployed to a number of other devices and platforms.

Diceworks was created by one artist and one programmer working together as a team. It's rare to find a single person who possesses both programming and artistic talent simultaneously; scientists say that these disciplines are split between two different lobes in our brains, and we tend to favor one or the other. The artist-programmer pairing that produced Diceworks is a common setup in game development. What's your own brain telling you? Are you more comfy with visuals or logic? Art or programming? Once you discover the answer, it's not a bad plan to find someone to make up the other half of your brain so that your game handles both areas competently.

At any event, with Diceworks we're definitely getting closer to the scope and scale that you can manage on your own as you start out with Unity.

It's also interesting to note that Diceworks is a 2D game created in a 3D engine. The third "D" is largely missing, and all of the game elements appear to exist on a flat plane. Nixing that extra dimension when you're just starting out isn't a half-bad idea. Adding depth to your game brings a whole new dimension of difficulty to your designs, and it will be easier to get up and running with Unity by focusing on the X and Y axes, and leaving the Z-axis in one of those dream jars. With a few sturdy working game examples under your belt, it won't be long before you can take that Z-jar down off the shelf and pop it open. The games that we'll be building in this book will stick to a two-dimensional plane, using three-dimensional models. Even so, certain games have taken this concept and ran with it: New Super Mario Bros. Wii locked its 3D characters to a 2D plane and wound up an extremely complex and satisfying platformer.

Lovers in a Dangerous Spacetime

With their game Lovers in a Dangerous Spacetime, the talented three-person team at the Asteroid Base adds half a "D" to that formula. This is a two-and-a-half-D game, which combines the advantages of a 2D game with all the eye-popping pizzazz of all 3Ds.

Showcase Showdown

Unity portals—game sites that feature Unity-made games—are popping up all over the place. Here are a few more sites to hit in your survey of what Unity can do:

 

Unity Technologies – "Made with Unity" page


http://unity3d.com/gallery/made-with-unity/game-list

Unity's own showcase of games features titles that aren't all playable, but they're sure to blow your mind.

 

Kongregate


http://www.kongregate.com/unity-games

Once the king of Flash game portals, Kongregate also features Unity-made games. Any developer can submit a game to Kongregate, and once the game is live, the Kongregate community can play, rate, and comment on it. If you're a first-time developer, that may sound a little scary. And if you're a veteran developer, you know exactly how scary it is! But an excellent goal for you to set, after reading this book, is to develop something of your own in Unity, and submit it to the scrutiny of complete strangers on a portal like Kongregate. Let's be honest... Mom is going to like everything you do. This may be your best shot at getting honest feedback, and it will help you grow as a developer.

 

The iOS App Store


Unity developers have taken to Apple's App Store in a big way. On any given day, a good number of the games on the "Top 100" list are Unity-made titles. For a particularly good time, try The Room, which is a short-and-sweet MYST-like game that will have you safe-cracking increasingly complex puzzle boxes nested inside one another. Again, a significant amount of time, talent, and effort went into creating The Room, but this tour is about getting a feel for what Unity can do—and what you can do with it (given enough time, talent, and effort!).

 

Walk before you can run (or double jump)


A common mistake that new game developers make is biting off more than they can chew. Even experienced game developers make this mistake when they get really excited about a project, or when they approach a new technology and expect to be immediately proficient at using it. The real danger here is that you'll sit down and try to create your dream—let's say it's a sword and sorcery RPG epic that combines all the best parts of League of Legends, ChuChu Rocket!, and Microsoft Excel. When you've sunk days and weeks and months into it and it still looks nothing like the game you envisioned, you give up. You figure that since you failed at creating your dream game, you were never really cut out to be a game developer to begin with.

You owe it to yourself to start small! Rome wasn't built in a day, and neither was your dream cart-racing game starring famous figures from Roman history. By taking smaller steps, you can experience success with a number of smaller games. Then you can take what you learn and add to it, slowly building your expertise until you're in a position to take that dream game jar off the shelf.

For now, let's keep our dream shelf fully stocked, and turn our attention to something small and achievable. By the end of this book, you'll have a collection of working games that started out simply, and grew more and more complex as you got smarter. My hope is that once you finish this book, you'll be well-equipped to dream up new incremental features for your games, and to hunt down the resources you will need to fill the gaps in your new-found knowledge.

In Chapter 2, Let's Start with the Sky, we'll go into detail about where you should start when you're deciding what kind of game to create. We'll also see some real-world examples of games that began as simple, effective ideas and later grew into enormously complex and feature-rich titles. From small acorns, mighty multiplayer oak tree games grow.

 

There's no such thing as "finished"


We'll be learning a lot about iteration throughout this book. Some game developers who produce content for fixed media like game disks and cartridges are used to producing a "gold master"—the final build of the game—and calling it a day. One of the joys of deploying games to the web or mobile is that they're never truly finished. You can continue tweaking your web games and modifying them until you end up with a far more fun and polished game than you started with.

If you follow Flashbang Studios on Twitter or if you read the studio's blog, you'll see that it's constantly modifying and improving its games, even years after they were "finished". The Flashbang team continued to tweak and modify Off-Road Velociraptor Safari even three years after the game was finished.

Likewise, we'll be creating some games that are raw and unfinished at first. But as we learn more about how to program the crucial bits and pieces common to many games, we'll keep revisiting our rough, early games to add those pieces and improve them.

 

Stop! Hammer time


Now that you've seen some of what Unity can do, it's time to download the program and kick the tires! The free version of Unity is available for a low price of... well, free (at the time of this writing) from the Unity 3D website.

  1. Go to http://unity3D.com.

  2. Click on the Download button.

  3. Download the latest version of the Unity 3D authoring tool for your platform—Mac or PC. If you are given the option, make sure to download the sample project along with the program.

  4. Follow all the onscreen prompts until the Unity authoring tool has finished installing.

  5. Launch Unity!

Fight Some Angry Bots

After a quick registration process, Unity is ready to go. With any luck, the AngryBots Demo will automatically open. If it doesn't, and you're faced with a dialogue asking you to open a project, you can find the AngryBots Demo in the following location by default:

  • Max OS: /Users/Shared/Unity/4-0_AngryBots

  • Windows XP: C:\Documents and Settings\All Users\Documents\Unity Projects\4-0_AngryBots

    or

  • C:\Documents and Settings\All Users\Shared Documents\Unity Projects\4-0_AngryBots

  • Windows 7/ 8/ Vista: C:\Users\Public\Public Documents\Unity Projects\4-0_AngryBots

If you thought you'd be a rebel and you unchecked the sample projects box when you downloaded Unity, you may find yourself re-downloading Unity to get the AngryBots Demo. You can pull down other sample learning projects, such as the AngryBots Demo from the Unity website:

http://unity3d.com/support/resources/example-projects/

Note

These paths may change depending on which version of Unity you've downloaded. As the Unity Technologies team improves the software, they launch new and more impressive demos to show off what Unity can do. If you're reading this book, and your copy of Unity 3D launches a different demo project, or if the Angry Bots Demo is no longer available by the time you begin reading this book, don't freak out! Everything we're about to discuss can be generally applied to most demos.

When the Angry Bots Demo first opens, you may see a splash screen referring you to different tutorial resources and language guides. How helpful! Now close it (don't worry, it'll be there next time, unless you uncheck the Show at Startup box). If you checked the box but you'd really like to see that welcome screen again, look in the menus under Help | Welcome Screen. In the menus, click on Window | Layouts | 2 by 3 to see the different panels that we're about to tour.

After the panels have repositioned themselves, look for the Project panel. It should be one of the three vertically oriented panels on the right half of your screen. At the top right of the Project panel is a very small button that looks like a downward-facing triangle next to three horizontal lines. Click there, and choose One Column Layout from the resulting context menu. This will get an annoying split view out of your way:

If you don't see all the fancy highfalutin' 3D jazz going on in the Scene and Game windows, you may just need to load the main game scene. To do this, find the Scene called AngryBots at the top of the Project panel (it has a black-and-white Unity icon next to it), and double-click it.

To try out the demo, click on the Play button at the top center of the screen:

You can walk around the Angry Bots Demo using the WASD keys on your keyboard. Hold down the left-mouse button to fire your boomstick at the aggravated automatons. When you're finished exploring, press the Esc key to pause the game and regain mouse control. Then click on the Play button again to end the demo:

 

The wonders of technology!


Much of what you see in the AngryBots Demo can't be built directly in Unity. Most of the assets were created with other software; Unity is the program you use to put everything together and to make it interactive. The Demo contains special models, such as the airlocks, which were imported from 3D software packages like 3D Studio Max, Maya, or Blender. Certain elements, like robot enemies, have scripts attached to them. Scripts are lists of instructions that tell the items in the game world how to behave.

Throughout the book, we'll learn how to import 3D models and write scripts to control them. Let's take a quick look around the Unity interface and note a few points of interest.

 

The Scene window


The Scene window is where you can position your GameObjects and move them around. This window has various controls to change its level of detail. Use these controls to toggle lighting on and off (in the editor only—not in your actual game), and to display the window contents with textures, wireframes, or a combination of both. You can use the colorful Gizmos at the top-right corner to constrain the view to the X, Y, and Z axes to view the top and sides of your scene. Click on the white box in the middle to return to Perspective view. This window also features a search field.

Try clicking on the gizmo's green Y cone to view the AngryBots Demo from above, and then type rock into the search field. Every object with rock in its name lights up, while the rest of the scene fades to grayscale. Click the tiny x button to clear the search field:

The Game window

The Game window shows you what your players will see. When you click on the Play button to test your game (as you just did with the Angry Bots Demo), the results of your efforts play out in this window. Toggle the Maximize on Play button to test your game in full-screen mode:

The Hierarchy panel

The Hierarchy panel lists all of the GameObjects in your Scene. GameObjects—cameras, lights, models, and prefabs—are the things that make up your game. They can be "tangible" things like the generators or the giant robot arm in the Angry Bots Demo. They can also include intangible things, which only you as the game developer get to see and play with, such as the cameras, the lights, the scripts, and colliders, which are special invisible shapes that tell the game engine when two game objects are touching.

The AngryBots Demo Hierarchy panel contains GameObjects for the cannisters, the tables, the airlocks and the computer terminals, to name a few. It also lists the Player, a very complicated GameObject that controls how the hero moves and collides with his environment. The player character has a camera following him. That camera is our eye into the game world. The Demo lists a collection called Environment(sounds)—a series of GameObject that determine what the player hears when he walks through different parts of the level (for example, torrential rain outside, and the droning equipment hum when he moves indoors). So, GameObject can include touchy-feely "physical" objects such as canisters and airlocks, as well as behind-the-scenes intangible things such as lights, cameras, and actions (scripts).

Click on a GameObject in the Hierarchy panel, and then hover your mouse over the Scene window. Press the F key on your keyboard, and the Scene window will automatically pan and zoom directly to that object. Alternatively, you can navigate to Edit | Frame Selected, which can be more reliable than using the keyboard shortcut. (I like to think of the F key standing for "Focus" to help me remember what this shortcut does). You can also double-click on the GameObjects in the Hierarchy panel.

The Project panel

The Project panel lists all of the elements that you'll use to create GameObjects in your project. For example, look for the mech_bot in the Objects | Enemies folder. The AngryBots Demo EnemyMech GameObjects is made up of a series of meshes that represent the mech's shape, a material to depict its "skin" or coloring, and an animation to describe its movement. All of these types of goodies are listed in the Project panel.

The Project panel displays the contents of a special folder called Assets on your computer's operating system. Unity automatically creates the Assets folder for you when you create a new project. If you drag a compatible file, like a 3D model, a sound effect, or an image into the Project panel, Unity copies it to the Assets folder behind the scenes, and displays it in the Project panel.

The Inspector panel

The Inspector is a context-sensitive panel, which means that it changes depending on what you select elsewhere in Unity. This is where you can adjust the position, rotation, and scale of GameObjects listed in the Hierarchy panel. The Inspector can also display controls to configure components that add functionality to the GameObjects. Between the three main panels in Unity (Hierarchy, Project, and Inspector), the Inspector is where you'll likely spend most of your time because that's where you'll be tweaking and fiddling with every aspect of the elements that comprise your game projects.

This screenshot of the Inspector panel shows the components attached to the Player GameObject in the Angry Bots Demo. This includes:

  • A number of scripts (including Free Movement Motor and Player Move Controller)

  • A Rigidbody component

  • A Capsule Collider

To see the same content on your computer, click to open the Player GameObject in the Hierarchy panel. In later chapters, we'll dive deeper to learn what these various components are all about.

Heads Up?

Let's use the Inspector panel to make a quick change to the orientation of the character. We'll begin the demo with the hero standing on his head (which is a sure-fire way to make those bots even angrier, by the way).

We can use the Inspector panel to change the rotation of the player. Follow these steps:

  1. In the Hierarchy panel, click to select the Player game object.

  2. Click on the Rotate button near the top left of the screen, which looks like two arrows sniffing each others' behinds:

    A globe appears around the bottom of the Player GameObject in the Scene view. (If you don't see the player, hover over the Scene view and press the F key on your keyboard.) The blue Z-axis rotator handle encircles the player's body. Clicking and dragging it rotates the player model as if he were standing in a very dodgy canoe. The red X-axis rotator handle rotates the player as if he was a foosball player, stuck on a metal rod. If we click and drag that handle, the player rotates to either fall flat on his face, or flat on his back, like he's got space sickness. And the green Y-axis rotator handle runs around the player like a hula hoop. Dragging this handle around makes the player spin to face different directions. The Player GameObject can get pretty hairy; in order to isolate the rotation controls, type player into the Scene window's search field to exclude all other GameObject.

  3. You can click-and-drag the red X-axis rotator handle to turn the player upside down, but a better method is to change the X-axis rotation in the Inspector panel. Expand the gray arrow next to Transform in the Inspector panel if it's not already open, and change the X value under Rotation to 180. The player flips upside down.

  4. Now, when you click on the Play button to test the game, the player will break-dance his way around the Angry Bots Demo, electric boogaloo-style. The robots are freaking out, thinking "ERROR! DOES NOT COMPUTE!" Way to keep them on their mechanical toes.

The Transform is the component that governs a GameObject's Position, Rotation, and Scale. Every object in the scene has a Transform component that determines where it is (Position), how big or small it is (Scale), and how it's oriented (Rotation). Objects can be stretched and deformed by scaling them along one axis, as we'll see in later chapters.

Layers and layout dropdowns

Above the Inspector panel, you'll see the Layer and Tag drop-down menus. Game objects can be grouped into layers, somewhat like in Photoshop or Flash. Unity stores a few commonly used layouts in the Layout drop-down menu (mine is set to the 2 by 3 configuration). You can also save and load your own custom layouts.

Playback controls

As we've seen, these three buttons help you test your game and control playback. The Play button starts and stops your game. The Pause button works as expected—it pauses your game so that you can make changes to it on the fly. The third button is a step-through control; use it to advance frame-by-frame through your game so that you can more tightly control what's going on.

Scene controls

At the top-left of your screen, you'll see four controls that help you move around your Scene, and position GameObjects within it. These controls are mapped to the Q, W, E, and R keys on your keyboard. From left to right, they are.

  • The Hand tool (Q): Use it to click-and-drag around your scene. Hold down the Alt key on your keyboard to rotate the view. Use your mouse wheel to zoom the scene in and out. Hold down the Shift key to pan, zoom, and rotate in larger increments to speed things up. This is a way for you to navigate around the game world. It doesn't actually impact the way the player sees the game. To modify the Game view, you need to use the Move or Rotate tools to modify the Camera position. Hold Shift to make the camera move farther. Hold the right or alternate mouse button to pivot the scene as if you're viewing it through a 3D camera.

  • The Move tool (W): This tool lets you move the GameObjects around your scene. You can either drag the object(s) around by the X, Y, or Z-axis handles, or by the square in the center for freeform movement. Holding down the Ctrl key or the command key (Apple) will snap movement to set grid increments.

  • The Rotate tool (E): Use it to spin your objects around using a neat spherical gizmo. The red, green, and blue lines map to the X, Y, and Z axes.

  • The Scale tool (R): This tool works much the same as the Move and Rotate tools. Use it to make your game objects larger or smaller. Dragging an X, Y, or Z handle will non-uniformly scale (squash and stretch) the object, while dragging the gray cube in the center will uniformly scale it.

 

Don't stop there – live a little!


We've glanced briefly at the key elements of the Unity interface, but there's no need to stop poking around. Far beyond the scope of this book, there is a wealth of menu options, buttons, and controls that we haven't covered. Why not explore those menus or start randomly clicking on things that you don't yet understand? Now is the time to safely break stuff. You didn't work hard to create the Angry Bots Demo, so why not mess around with it a little bit?

Some of the changes you make to the Demo will "stick", even if you don't explicitly choose to save your changes. Duplicate the entire Angry Bots Demo folder before you go crazy.

Here are some things to try:

  • Select some of the GameObjects in the Hierarchy panel and move them around in the Scene window using the Scene controls. What happens when you put an airlock in the middle of the sky? Can the player still pass through? What if you put the canisters or the computers over the player's head before the game starts? Do they fall, or do they hover? Can you remove objects to help the player careen off the edge of the balcony? What happens when he does?

  • Randomly right-click / alternate-click in the three different panels and read through the context menu options to see what you're getting yourself into.

  • Poke around in the GameObject | Create Other menu. There's a whole list of interesting things that you can add to this scene without even touching a 3D modeling program.

  • What happens when you delete the lights from the scene? Or the camera? Can you add another camera? More lights? How does that affect the Scene?

  • Can you move the player to another part of the Demo to change your starting position? Can you replace the audio files to make the gun "moo" whenever you fire it?

  • Download a picture of kittens from the Internet and see if you can wrap it around a boulder model. Kittens rock! You can pull the kitties into your project using the Assets | Import New Asset option in the menu.

 

Summary


This chapter was all about getting a feel for what Unity can do and for what the program interface had to offer. Here's what we found out:

  • Massive 80-person teams, all the way down to tiny one- or two-person teams are using Unity to create fun games.

  • By thinking small, we'll have more success in learning Unity and producing fully functional games instead of huge but half-baked abandoned projects.

  • Different flavors of Unity help us deploy our games to different platforms. By using the free version, we can deploy to the web, and to Mac, PC, Linux, and certain mobile platforms.

  • The Unity interface has controls and panels that let us visually compose our game assets, and test games on the fly right inside the program!

I hope you've taken some time to thoroughly vandalize the Angry Bots Demo. If you save the file by clicking on File | Save Project, you'll have a perma-upside-down space marine in your Demo. If you want to return to a pristine AngryBots Demo later to wreak more havoc, don't bother saving the hilarious (but meaningless) changes we've made in this chapter.

Big ambition, tiny games

Now that we've trashed the joint, let's take a quick trip through some game design theory. In the next chapter, we'll figure out the scope and scale of a game that a solo, beginner developer should actually tackle. Crack your knuckles and put on your favorite hat because you're about to dip yourself in awesome sauce.

About the Author
  • Ryan Henson Creighton

    Ryan is the founder of Untold Entertainment Inc., a boutique game development studio in the heart of downtown Toronto. Ryan got his start at a Canadian television broadcaster creating small, simple games for kids and preschoolers. By the time he was through, he had built over fifty games for a wide range of clients including McDonalds, Hasbro, Lego, Proctor and Gamble, Nickelodeon, and the Canadian National Institute for the Blind. These games ran the gamut from simple slider puzzles, memory games, and contest entry mechanics to tile-based graphic adventure games and massively multiplayer virtual worlds. Ryan often leveraged his theatre background to perform on-camera in promotional spots for Microsoft and Nintendo. He spent a number of years moonlighting as a video game journalist under the cartoonish moniker "MrSock".Ryan founded Untold Entertainment Inc. in 2007 and has continued to develop great kids' content with broadcasters and independent television producers to help extend their on-air brands online. He packs the company's popular blog with tutorials, designer diaries, and insights into the world of independent game development, employing his signature biting wit and ludicrous photo captions.Through Untold Entertainment, Ryan is developing a number of original properties, which include: Interrupting Cow Trivia, an online multiplayer trivia game; Spellirium, a word puzzle/adventure game hybrid; UGAGS, the Untold Graphic Adventure Game System; and Kahoots, a fun crime-themed puzzle game modeled entirely in clay. Ryan lives and bikes around downtown Toronto with his wife Cheryl, and his two tiny daughters Cassandra and Isabel.

    Browse publications by this author