39,59 €
Game engines are central to the video games we know and love. From the artwork to the mathematics that underpin the frames onscreen, the engine calls the shots. Aside from offering one of the leading 3D game engines, Unity also provides a superlative development tool ñ a tool that can produce professional standard games for Mac, PC, and the Unity Web Player.
This book is a complete exercise in game development covering environments, physics, sound, particles, and much more, to get you up and working with Unity quickly.
Taking a practical approach, this book will introduce you to the concepts of developing 3D games before getting to grips with development in Unity itself. From creating 3D worlds to scripting and creating simple game elements you will learn everything you'll need to get started with game development for the PC, Mac, and Web.
This book is designed to cover a set of easy to follow examples, which culminate in the production of a First Person 3D game, complete with an interactive island environment. By introducing common concepts of game and 3D production, you'll explore Unity to make a character interact with the game world, and build puzzles for the player to solve, in order to complete the game. At the end of the book, you will have a fully working 3D game and all the skills required to extend the game further, giving your end-user, the player, the best experience possible. Soon you will be creating your own 3D games with ease!
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 437
Veröffentlichungsjahr: 2009
Copyright © 2009 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or 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 information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: October 2009
Production Reference: 1250909
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847198-18-1
www.packtpub.com
Cover Image by Charles Hinshaw (<[email protected]>)
Author
Will Goldstone
Reviewers
Aaron Cross
Emil E. Johansen
Clifford Peters
Jonathan Sykes
Acquisition Editor
James Lumsden
Development Editor
Amey Kanse
Technical Editors
Shadab Khan
Smita Solanki
Copy Editor
Leonard D'Silva
Indexer
Monica Ajmera
Editorial Team Leader
Akshara Aware
Project Team Leader
Priya Mukherji
Project Coordinator
Zainab Bagasrawala
Proofreader
Sandra Hopper
Graphics
Nilesh R. Mohite
Production Coordinators
Adline Swetha Jesuthas
Aparna Bhagat
Cover Work
Adline Swetha Jesuthas
Will Goldstone is an interactive designer and tutor based in the south west of England. Spending much of his time online, he focuses on web design and game development, specializing in online tutoring of many interactive disciplines.
Having discovered Unity in its first version, he has been working to promote its 'game development for everyone' ethic ever since and works with Unity to produce online games and games for the Apple-iPhone platform.
Will is reachable through his blog at www.willgoldstone.com, where you can find links to his various other online activities. He spends his free time on graphics designing, photography, writing loud music, and playing frisbee on the beach.
I would like to thank my fantastic family and friends for supporting me during the production of this book—it wouldn't be here without you! Massive thanks also to the members of the Unity Technologies team and Unity IRC channel whose tireless patience got me started in Unity development back when; big thanks especially to Dan Blacker, Joachim Ante, Emil Johansen, Cliff Peters, Tom Higgins, Charles Hinshaw, Neil Carter, ToreTank, Mike Mac, Duckets, Joe Robins, Daniel Brauer, Dock, oPless, Thomas Lund, Digitalos and anyone else I've neglectfully forgotten. A massive cheers to all of you; you guys rock.
Aaron Cross is a freelance video game developer based in New Zealand. A successful musician and music producer, film-maker, and 3D artist, he switched his focus to game development in 2006. Since then he has produced three video game titles, and has provided art and programming solutions to Unity developers across the globe. He is based in Wellington, New Zealand.
In addition to commercial games, he has developed simulations for medical training, architectural visualization, science and research, conservation, and visual reconstructions for evidence used in court cases, using the Unity game engine.
I would like to acknowledge the creators of this amazing program, this amazing tool that allows the ultimate digital experience in creative expression. I've done a lot of things in my life, but only when I found the gateway to real-time development through Unity did I finally realize that I could be really passionate and successful at the same time. My imagination has turned into a tangible reality with this tool, and it's become a foundation to my professional success. I can't thank you enough. I'd also like to thank my clients for being part of the fun! Many of you have become good friends over the code and polygons, late nights, and creative successes. And finally, I'd like to thank Gavin Hewitt, who taught me all the hard stuff, but also taught me how to love pencils and paper, and got me on good firm ground right from the start...
Enjoy your work my friends!
Emil E. Johansen is a freelance game development consultant living in Copenhagen, Denmark. Having worked professionally with engines, such as Renderware, CryEngine, and UnrealEngine 3, Emil joined the Unity community when going freelance and has been very active there by the alias AngryAnt.
In the Unity community, Emil has actively promoted and participated in the Wiki and IRC channels, while developing AI middleware solutions for Unity.
When not hooked up to the internet, Emil enjoys biking, sailing, and concert going. Online he can be found on the Unity forums, Wiki, and IRC channel as AngryAnt, on Twitter by the same name, and at AngryAnt.com.
Clifford Peters is 19 years old and has recently graduated from high school. A few years ago, Clifford decided to make his own web site. He learned about HTML and started to hand code his own web site. Later, he rewrote his web site after learning about XHTML and CSS. Later, after getting bored with making a web site, Clifford decided that he would instead make a computer game. He tried a bunch of different game engines but did not like using them very much. Clifford then found out about Unity, and after using it for a few weeks, he realized that he liked it because it was easy to use. He liked it so much that he went and bought it, and now he often spends hours a day programming with Unity and developing games.
Jonathan Sykes is a senior play researcher, skilled in the design and evaluation of the play experience. He is the director of eMotionLab, a premier research facility, which offers both consultancy and development services in the area of game production and play-testing. His particular research focus is the application of play technologies to serious endeavors, such as health, education, and business.
Both a psychologist and usability engineer, Jonathan's work is very much player-centered, and focused on the player experience. He has worked with Microsoft's Game User Research group to develop player-centered approaches to game design and evaluation and written academic papers and textbook chapters on the subject. He also works as a senior lecturer at Glasgow Caledonian University where he delivers undergraduate courses in player-centered game development.
Unity is a 3D game authoring tool for Mac and PC. Game engines are the nuts and bolts that sit behind the scenes of every video game. From the artwork right down to the mathematics that decide every frame on screen, the "engine" makes the decisions. Starting out with rendering—the method of displaying graphics on screen, and integrating a control method and a set of rules for the game to follow—the engine is what a developer builds to "house" the game. Modern 3D game engines are a deluge of meticulously written code, and as such, once used for their intended purpose (which is the production of a game they are made for), these engines are often sold, modified, and reused. An obvious example of this is the Epic Games Unreal Engine. Originally developed in the late 90s for Unreal—a PC First Person Shooter—the engine has gone on to see massive success in its more recent incarnations, being licensed by other developers for literally hundreds of commercial games and simulations.
Due to the level of complexity and cost of such commercial game engines, the game development industry is a difficult area of interest for potential fresh talent to break into, without studying programming languages such as C++ extensively. Modern console and computer games are built around C++ as it is currently the most efficient language in terms of computational speed, and as such, the structure and commands of commercial games engines require thousands upon thousands of such lines of code to function. This code is delivered in Unity with the help of just-in-time compilation (known as JIT), using the open source C++ library Mono. By using JIT compilation, engines such as Unity can take advantage of high-speed compilation, whereby the code you will write for Unity is compiled to Mono just before it is executed. This is crucial for games that must execute code at specific moments during runtime. In addition to the Mono library, Unity also takes advantage of other software libraries in its functionality, such as Nvidia's PhysX physics engine, OpenGL, and DirectX for 3D rendering and OpenAL for audio. All these libraries are built into the application, so you will not need to worry about learning how to use them individually. So, simply sit back and enjoy them working for you seamlessly within Unity.
The developers of engines also build tools with which to command the functional coding they have created. For example, the creation of an outdoor terrain is held in a set of instructions which define its shape (or topography), visual appearance, and even how it responds to deformation in game. But this set of instructions would be inefficient as a part of the game engine were it not attached to a visual tool to control the aforementioned properties. This is where a Graphical User Interface (GUI) comes in. Game engine developers will often build an interface of tools to aid their team in manipulating parts of the engine in order to save time in the development process and make the engine accessible to potential buyers, post production. This is also true of Unity, as it has a very strong community of users that share their tools in the form of plugins for the package. Visit the Unify community wiki at http://www.unifycommunity.com/wiki for more information.
For many new potential developers, the steep learning curve required to pick up programming languages such as C++, or the engines that utilize it, is simply too great a task to attempt. Without completing degree-level studies in programming or computer animation, it is difficult for many enthusiasts to get started in learning the concepts, methods, and design principles involved in game production. Unity Technologies is one such company that has set out to rectify this. Starting with their own game engine in 2001, the Danish-based game development company endeavoured to strip down their complex game development tools and make a simple, user-driven package that anyone could pick up and begin experimenting with. The team resolved to keep the source code that drives the engine behind the scenes, instead providing a complete GUI (Graphical User Interface) that allows the user to control the powerful engine source code without ever having to create parts of it themselves. This factor has made Unity highly popular with new developers, and is likely one of the key reasons you're reading this book. By establishing logical concepts and categorizing common methods involved in game production, Unity puts the power of its engine into the user's hands, allowing maximum results with minimal effort, thereby encouraging experimentation with the most crucial factor of all—gameplay.
Having appealed to many games developers, Unity has filled a gap in the games development market that few others can fully claim to cater to. Having the ability to produce professional standard games, publish 3D to both Mac and PC, as well as having its own Web Player, Unity is one of the fastest growing game engines in its sector. The engine also has its own Nintendo Wii and Apple iPhone developing versions, meaning that once you have mastered the basics, a pipeline to not only home computer, but also to console and mobile development lies ahead of you.
The fast pace of the entertainment and marketing industries requires a quick turnaround of gaming media. Also, many companies are now looking to packages such as Unity to enable their creatives to produce better products with the greatest of ease. With 2009 seeing the release of Unity version 2.5, and its first steps onto PC format, its usage looks set to skyrocket. But what is Unity? How does it work? What can it do? And most importantly, how can it get you get started on the path to 3D game development in just a few weeks?
This book is designed to cover a set of easy-to-follow examples, which culminate in the production of a First-Person-viewed 3D game, complete with an interactive island environment. By introducing common concepts of game and 3D production, we'll explore the use of Unity to make a player character interact with the game world, and build puzzles for the player to solve in order to complete the game.
Here's a quick chapter-by-chapter overview of what will be covered:
This chapter covers the key concepts we'll need to understand and complete the exercise in this book. It takes a brief look at 3D concepts and the processes used by Unity to create games.
Our game world is but an empty void! We'll kick off with this chapter by taking a look at the various ways to incorporate terrains, externally produced 3D models, and other Unity engine features such as sound and lighting to get your game environment up and running.
Every game needs a hero, right? In this chapter, we'll be taking a look at every element that goes into making the first-person player character from input controls to cameras and colliders. Once you've learnt what goes into making him, you'll introduce the player character to your island and take a stroll around.
Games are all about interacting with a virtual world, so where would our character be without some in-game actions? In this chapter, I'll introduce you to collision detection and ray casting. We'll look at how we can combine these techniques with scripting and animation to transform our static building into one that responds to our player.
Giving your player a sense of achievement in your game is essential. To help with this, you'll need to remind them of actions they've taken so far in the game, and give them something to aim for. In this fifth chapter, we will construct what is often referred to as a Heads Up Display (HUD) with text and graphical displays that change dynamically as the user plays.
Having created a simple HUD, you'll create a short object-collection game, which will allow the player character to pick up batteries in order to gain access to the building on the island.
Almost every game scenario that you can imagine will involve creating or "spawning" objects in your environment. Known in programming terms as Instantiation, the creation of objects during the game's runtime is a crucial concept for every beginner developer to get to grips with.
Having created our collection game and building interaction in previous chapters, we'll be building upon the interactivity in our game by creating a basic target game, which will involve throwing objects at targets to unlock a part of our environment. This will not only teach you about instantiation, but also the crucial concept of using rigid body physics objects in your games.
What's a 3D game these days without some fancy graphic effects to wow the player? In this chapter, you'll be creating a log fire to keep our player warm — using two particle systems, one for flames and the other for smoke.
Using a Particle System, we'll look at how we can mimic the behavior of fire and utilize images for each particle to add realism; we'll finish by disabling the fire, giving the player something to aim for — getting it lit to keep warm!
Creating a professional, easy-to-navigate menu is a crucial part of making an enjoyable game product. What user is going to want to play your game if he or she can't even find the Start button? In this chapter, we look at the various ways of creating menus and other user interfaces for the player to interact with.
You will create menus using both GUI textures and the GUI class in order to create scalable interfaces that can be deployed on the desktop or the Web.
In game production, especially in Unity, you will reach a point at which you have just created some piece of interaction in your game that you're so pleased with, you want to add that extra polish to make it really stand out to the player.
In this chapter we'll take a look at further uses of sound, lighting effects, trail rendering, and other dynamic effects that are easy to implement, and make the difference between a simple working game and a polished final product.
In this chapter, we will look at how we can export your game for the Web and as a standalone project. We'll look at various different settings you will need to consider when you are preparing your finished product for your audience, such as graphical quality, control input, and more.
In this chapter, we will discuss the ways in which you should move on from this book, and how you can gather information from test users to improve your game. This will help you prepare your project to be tested by a wider audience to get feedback and make even better games!
Having worked with Unity for the past few years as a tutor, I've found the main complaint that its users encounter is not with the software itself, but rather that there is a lack of introductory material for new users coming from a non-programming based background.
In the existing climate, this is, of course, rare; but with a tool such as Unity allowing such ease of production as it does, the importance of such a tutorial guide has become ever more pressing.
If you're a designer or animator who wishes to make their first steps into game development, or if you've simply spent many hours seated in front of video games, with ideas bubbling away in the back of your mind, Unity and this book could be your ideal starting point. I will assume no prior knowledge of game production and start completely from scratch, inviting you to simply bring with you a passion for making great games.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
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.
Visit http://www.packtpub.com/files/code/8181_Code.zip to directly download the asset packages you will need to use to complete this book.
The package also contains example code for the programming parts of the book.
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection 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 location address or web site name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Before getting started with any 3D package, it is crucial to understand the environment you'll be working in. As Unity is primarily a 3D-based development tool, many concepts throughout this book will assume a certain level of understanding of 3D development and game engines. It is crucial that you equip yourself with an understanding of these concepts before diving into the practical elements of the rest of this book.
Let's take a look at the crucial elements of 3D worlds, and how Unity lets you develop games in the third dimension.
If you have worked with any 3D artworking application before, you'll likely be familiar with the concept of the Z-axis. The Z-axis, in addition to the existing X for horizontal and Y for vertical, represents depth. In 3D applications, you'll see information on objects laid out in X, Y, Z format—this is known as the Cartesian coordinate method. Dimensions, rotational values, and positions in the 3D world can all be described in this way. In this book, like in other documentation of 3D, you'll see such information written with parenthesis, shown as follows:
(10, 15, 10)
This is mostly for neatness, and also due to the fact that in programming, these values must be written in this way. Regardless of their presentation, you can assume that any sets of three values separated by commas will be in X, Y, Z order.
A crucial concept to begin looking at is the difference between Localspace and World space. In any 3D package, the world you will work in is technically infinite, and it can be difficult to keep track of the location of objects within it. In every 3D world, there is a point of origin, often referred to as zero, as it is represented by the position (0,0,0).
All world positions of objects in 3D are relative to world zero. However, to make things simpler, we also use Local space (also known as Object space) to define object positions in relation to one another. Local space assumes that every object has its own zero point, which is the point from which its axis handles emerge. This is usually the center of the object, and by creating relationships between objects, we can compare their positions in relation to one another. Such relationships, known as parent-childrelationships, mean that we can calculate distances from other objects using Local space, with the parent object's position becoming the new zero point for any of its child objects. For more information on parent-child relationships, see Chapter 3.
You'll also see 3D vectors described in Cartesian coordinates. Like their 2D counterparts, 3D vectors are simply lines drawn in the 3D world that have a direction and a length. Vectors can be moved in world space, but remain unchanged themselves. Vectors are useful in a game engine context, as they allow us to calculate distances, relative angles between objects, and the direction of objects.
Cameras are essential in the 3D world, as they act as the viewport for the screen. Having a pyramid-shaped field of vision, cameras can be placed at any point in the world, animated, or attached to characters or objects as part of a game scenario.
With adjustable Field of Vision (FOV), 3D cameras are your viewport on the 3D world. In game engines, you'll notice that effects such as lighting, motion blurs, and other effects are applied to the camera to help with game simulation of a person's eye view of the world—you can even add a few cinematic effects that the human eye will never experience, such as lens flares when looking at the sun!
Most modern 3D games utilize multiple cameras to show parts of the game world that the character camera is not currently looking at—like a 'cutaway' in cinematic terms. Unity does this with ease by allowing many cameras in a single scene, which can be scripted to act as the main camera at any point during runtime. Multiple cameras can also be used in a game to control the rendering of particular 2D and 3D elements separately as part of the optimization process. For example, objects may be grouped in layers, and cameras may be assigned to render objects in particular layers. This gives us more control over individual renders of certain elements in the game.
In constructing 3D shapes, all objects are ultimately made up of interconnected 2D shapes known as polygons. On importing models from a modelling application, Unity converts all polygons to polygon triangles. Polygon triangles (also referred to as faces) are in turn made up of three connected edges. The locations at which these vertices meet are known as points or vertices. By knowing these locations, game engines are able to make calculations regarding the points of impact, known as collisions, when using complex collision detection with Mesh Colliders, such as in shooting games to detect the exact location at which a bullet has hit another object. By combining many linked polygons, 3D modelling applications allow us to build complex shapes, known as meshes. In addition to building 3D shapes, the data stored in meshes can have many other uses. For example, it can be used as surface navigational data by making objects in a game, by following the vertices.
In game projects, it is crucial for the developer to understand the importance of polygon count. The polygon count is the total number of polygons, often in reference to a model, but also in reference to an entire game level. The higher the number of polygons, the more work your computer must do to render the objects onscreen. This is why, in the past decade or so, we've seen an increase in the level of detail from early 3D games to those of today—simply compare the visual detail in a game, such as Id's Quake(1996) with the details seen in a game, such as Epic's Gears Of War (2006). As a result of faster technology, game developers are now able to model 3D characters and worlds for games that contain a much higher polygon count and this trend will inevitably continue.
Materials are a common concept to all 3D applications, as they provide the means to set the visual appearance of a 3D model. From basic colors to reflective image-based surfaces, materials handle everything.
Starting with a simple color and the option of using one or more images—known as textures—in a single material, the material works with the shader, which is a script in charge of the style of rendering. For example, in a reflective shader, the material will render reflections of surrounding objects, but maintain its color or the look of the image applied as its texture.
In Unity, the use of materials is easy. Any materials created in your 3D modelling package will be imported and recreated automatically by the engine and created as assets to use later. You can also create your own materials from scratch, assigning images as texture files, and selecting a shader from a large library that comes built-in. You may also write your own shader scripts, or implement those written by members of the Unity community, giving you more freedom for expansion beyond the included set.
Crucially, when creating textures for a game in a graphics package such as Photoshop, you must be aware of the resolution. Game textures are expected to be square, and sized to a power of 2. This means that numbers should run as follows:
Creating textures of these sizes will mean that they can be tiled successfully by the game engine. You should also be aware that the larger the texture file you use, the more processing power you'll be demanding from the player's computer. Therefore, always remember to try resizing your graphics to the smallest power of 2 dimensions possible, without sacrificing too much in the way of quality.
For developers working with game engines, physics engines provide an accompanying way of simulating real-world responses for objects in games. In Unity, the game engine uses Nvidia's PhysX engine, a popular and highly accurate commercial physics engine.
In game engines, there is no assumption that an object should be affected by physics—firstly because it requires a lot of processing power, and secondly because it simply doesn't make sense. For example, in a 3D driving game, it makes sense for the cars to be under the influence of the physics engine, but not the track or surrounding objects, such as trees, walls, and so on—they simply don't need to be. For this reason, when making games, a Rigid Body component is given to any object you want under the control of the physics engine.
Physics engines for games use the Rigid Body dynamics system of creating realistic motion. This simply means that instead of objects being static in the 3D world, they can have the following properties:
As the power of hardware and software increases, rigid body physics is becoming more widely applied in games, as it offers the potential for more varied and realistic simulation. We'll be utilizing rigid body dynamics as part of our game in Chapter 6.
While more crucial in game engines than in 3D animation, collision detection is the way we analyze our 3D world for inter-object collisions. By giving an object a Collider component, we are effectively placing an invisible net around it. This net mimics its shape and is in charge of reporting any collisions with other colliders, making the game engine respond accordingly. For example, in a ten-pin bowling game, a simple spherical collider will surround the ball, while the pins themselves will have either a simple capsule collider, or for a more realistic collision, employ a Mesh collider. On impact, the colliders of any affected objects will report to the physics engine, which will dictate their reaction, based on the direction of impact, speed, and other factors.
In this example, employing a mesh collider to fit exactly to the shape of the pin model would be more accurate but is more expensive in processing terms. This simply means that it demands more processing power from the computer, the cost of which is reflected in slower performance—hence the term expensive.
Unity makes the game production process simple by giving you a set of logical steps to build any conceivable game scenario. Renowned for being non-game-type specific, Unity offers you a blank canvas and a set of consistent procedures to let your imagination be the limit of your creativity. By establishing its use of the Game Object (GO) concept, you are able to break down parts of your game into easily manageable objects, which are made of many individual Component parts. By making individual objects within the game and introducing functionality to them with each component you add, you are able to infinitely expand your game in a logical progressive manner. Component parts in turn have variables—essentially settings to control them with. By adjusting these variables, you'll have complete control over the effect that Component has on your object. Let's take a look at a simple example.
If I wished to have a bouncing ball as part of a game, then I'd begin with a sphere. This can quickly be created from the Unity menus, and will give you a new Game Object with a sphere mesh (a net of a 3D shape), and a Renderer component to make it visible. Having created this, I can then add a Rigid body. A Rigidbody (Unity refers to most two-word phrases as a single word term) is a component which tells Unity to apply its physics engine to an object. With this comes mass, gravity, and the ability to apply forces to the object, either when the player commands it or simply when it collides with another object. Our sphere will now fall to the ground when the game runs, but how do we make it bounce? This is simple! The collider component has a variable called Physic Material—this is a setting for the Rigidbody, defining how it will react to other objects' surfaces. Here we can select Bouncy, an available preset, and voila! Our bouncing ball is complete, in only a few clicks.
This streamlined approach for the most basic of tasks, such as the previous example, seems pedestrian at first. However, you'll soon find that by applying this approach to more complex tasks, they become very simple to achieve. Here is an overview of those key Unity concepts plus a few more.
These are the building blocks of all Unity projects. From graphics in the form of image files, through 3D models and sound files, Unity refers to the files you'll use to create your game as assets. This is why in any Unity project folder all files used are stored in a child folder named Assets.
This book consists of code files and assets uploaded on our web site (www.packtpub.com/files/code/8181_Code.zip) and available for extraction here. Please extract the files from the already mentioned link to take advantage of the asset codes, an integral part of unity game development.
In Unity, you should think of scenes as individual levels, or areas of game content (such as menus). By constructing your game with many scenes, you'll be able to distribute loading times and test different parts of your game individually.
When an asset is used in a game scene, it becomes a new Game Object—referred to in Unity terms—especially in scripting—using the contracted term "GameObject". All GameObjects contain at least one component to begin with, that is, the Transform component. Transform simply tells the Unity engine the position, rotation, and scale of an object—all described in X, Y, Z coordinate (or in the case of scale, dimensional) order. In turn, the component can then be addressed in scripting in order to set an object's position, rotation, or scale. From this initial component, you will build upon game objects with further components adding required functionality to build every part of any game scenario you can imagine.
Components come in various forms. They can be for creating behavior, defining appearance, and influencing other aspects of an object's function in the game. By 'attaching' components to an object, you can immediately apply new parts of the game engine to your object. Common components of game production come built-in with Unity, such as the Rigidbody component mentioned earlier, down to simpler elements such as lights, cameras, particle emitters, and more. To build further interactive elements of the game, you'll write scripts, which are treated as components in Unity.
While being considered by Unity to be Components, scripts are an essential part of game production, and deserve a mention as a key concept. In this book, we'll write our scripts in JavaScript, but you should be aware that Unity offers you the opportunity to write in C# and Boo (a derivative of the Python language) also. I've chosen to demonstrate Unity with JavaScript, as it is a functional programming language, with a simple to follow syntax that some of you may already have encountered in other endeavors such as Adobe Flash development in ActionScript or in using JavaScript itself for web development.
Unity does not require you to learn how the coding of its own engine works or how to modify it, but you will be utilizing scripting in almost every game scenario you develop. The beauty of using Unity scripting is that any script you write for your game will be straightforward enough after a few examples, as Unity has its own built-in Behavior class—a set of scripting instructions for you to call upon. For many new developers, getting to grips with scripting can be a daunting prospect, and one that threatens to put off new Unity users who are simply accustomed to design only. I will introduce scripting one step at a time, with a mind to showing you not only the importance, but also the power of effective scripting for your Unity games.
To write scripts, you'll use Unity's standalone script editor. On Mac, this is an application called Unitron, and on PC, Uniscite. These separate applications can be found in the Unity application folder on your PC or Mac and will be launched any time you edit a new script or an existing one. Amending and saving scripts in the script editor will immediately update the script in Unity. You may also designate your own script editor in the Unity preferences if you wish.
Unity's development approach hinges around the GameObject concept, but it also has a clever way to store objects as assets to be reused in different parts of your game, and then 'spawned' or 'cloned' at any time. By creating complex objects with various components and settings, you'll be effectively building a template for something you may want to spawn multiple instances of, with each instance then being individually modifiable. Consider a crate as an example—you may have given the object in the game a mass, and written scripted behaviors for its destruction; chances are you'll want to use this object more than once in a game, and perhaps even in games other than the one it was designed for.
Prefabs allow you to store the object, complete with components and current configuration. Comparable to the MovieClip concept in Adobe Flash, think of prefabs simply as empty containers that you can fill with objects to form a data template you'll likely recycle.
The Unity interface, like many other working environments, has a customizable layout. Consisting of several dockable spaces, you can pick which parts of the interface appear where. Let's take a look at a typical Unity layout:
As the previous image demonstrates (PC version shown), there are five different elements you'll be dealing with:
The Scene window is where you will build the entirety of your game project in Unity. This window offers a perspective (full 3D) view, which is switchable to orthographic (top down, side on, and front on) views. This acts as a fully rendered 'Editor' view of the game world you build. Dragging an asset to this window will make it an active game object. The Scene view is tied to the Hierarchy, which lists all active objects in the currently open scene in ascending alphabetical order.
The Scene window is also accompanied by four useful control buttons, as shown in the previous image. Accessible from the keyboard using keys Q, W, E, and R, these keys perform the following operations:
Having selected objects in either the Scene or Hierarchy, they immediately get selected in both. Selection of objects in this way will also show the properties of the object in the Inspector. Given that you may not be able to see an object you've selected in the Hierarchy in the Scene window, Unity also provides the use of the F key, to focus your Scene view on that object. Simply select an object from the Hierarchy, hover your mouse cursor over the Scene window, and press F.
Think of the Inspector as your personal toolkit to adjust every element of any game object or asset in your project. Much like the Property Inspector concept utilized by Adobe in Flash and Dreamweaver, this is a context-sensitive window. All this means is that whatever you select, the Inspector will change to show its relevant properties—it is sensitive to the context in which you are working.
The Inspector will show every component part of anything you select, and allow you to adjust the variables of these components, using simple form elements such as text input boxes, slider scales, buttons, and drop-down menus. Many of these variables are tied into Unity's drag-and-drop system, which means that rather than selecting from a drop-down menu, if it is more convenient, you can drag-and-drop to choose settings.
This window is not only for inspecting objects. It will also change to show the various options for your project when choosing them from the Edit menu, as it acts as an ideal space to show you preferences—changing back to showing component properties as soon as you reselect an object or asset.
In this screenshot, the Inspector is showing properties for a target object in the game. The object itself features two components—Transform and Animation. The Inspector will allow you to make changes to settings in either of them. Also notice that to temporarily disable any component at any time—which will become very useful for testing and experimentation—you can simply deselect the box to the left of the component's name. Likewise, if you wish to switch off an entire object at a time, then you may deselect the box next to its name at the top of the Inspector window.
The Project window is a direct view of the Assets folder of your project. Every Unity project is made up of a parent folder, containing three subfolders—Assets, Library, and while the Unity Editor is running, a Temp folder. Placing assets into the Assets folder means you'll immediately be able to see them in the Project window, and they'll also be automatically imported into your Unity project. Likewise, changing any asset located in the Assets folder, and resaving it from a third-party application, such as Photoshop, will cause Unity to reimport the asset, reflecting your changes immediately in your project and any active scenes that use that particular asset.
It is important to remember that you should only alter asset locations and names using the Project window—using Finder (Mac) or Windows Explorer (PC) to do so may break connections in your Unity project. Therefore, to relocate or rename objects in your Assets folder, use Unity's Project window instead.
The Project window is accompanied by a Create
