Statistics
4
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-24

AuthorParis Buttfield-Addison, Jon Manning, Tim Nugent

Discover how to use the Unity game engine to its full potential for both 3D and 2D game development—from the basics of scripting to useful tricks in gameplay, behavior, and animation. With this problem-solving cookbook, you’ll get started in two ways: First, you’ll learn about the Unity game engine through brief recipes that teach specific features of the software and scripting systems. Second, you’ll apply a collection of snippets to address common gameplay scenarios, such as properly keeping score. Using our cookbook format, we pinpoint the problem, set out the solution, and discuss how to solve your problem in the best and most straightforward way possible. This book is ideal for beginning to intermediate Unity developers. You’ll find solutions for: • 2D and 3D graphics • Math, physics, and character control • Animation and movement • Behavior and AI • Sound and music • Input and gameplay • Scripting and user interface

Tags
No tags
ISBN: 1491999152
Publisher: O'Reilly Media, Incorporated
Publish Year: 2019
Language: 英文
Pages: 356
File Format: PDF
File Size: 12.3 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Unity Game Development Cookbook From the Basics to Virtual Reality Paris Buttfield-Addison, Jon Manning, and Tim Nugent
Unity Game Development Cookbook by Paris Buttfield-Addison, Jon Manning, and Tim Nugent Copyright © 2019 Secret Lab. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. • Editors: Rachel Roumeliotis and Jeff Bleiel • Production Editor: Deborah Baker • Copyeditor: Rachel Monaghan • Proofreader: Kim Cofer • Indexer: Judy McConville • Interior Designer: David Futato • Cover Designer: Karen Montgomery • Illustrator: Rebecca Demarest • April 2019: First Edition Revision History for the First Edition • 2019-02-22: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491999158 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Unity Game Development Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-99915-8
Preface Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion. NOTE This element signifies a general note. WARNING This element indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Unity Game Development Cookbook by Paris Buttfield-Addison, Jon Manning, and Tim Nugent (O’Reilly). Copyright 2019 Secret Lab, 978-1-491-99915-8.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly NOTE For almost 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, conferences, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, please visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: • O’Reilly Media, Inc. • 1005 Gravenstein Highway North • Sebastopol, CA 95472 • 800-998-9938 (in the United States or Canada) • 707-829-0515 (international or local) • 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://www.oreilly.com/catalog/unity-game- development/9781491999141/. To comment or ask technical questions about this book, send email to bookquestions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia
Chapter 1. Working with Unity In order to make things in Unity, it’s important to understand how Unity works and how to work with it as a piece of software. In this chapter, we’ll take a tour through the interface and features of Unity, so that you’ll be ready to start building things in the editor. TIP If you’re new to Unity, we recommend reading all the recipes in this chapter, as well as in Chapter 2, before trying other recipes in this book. This chapter also introduces you to many of the terms used in the Unity ecosystem, which will help you make sense of the rest of this book. 1.1 Getting Around in Unity Problem You want to learn how to navigate the Unity editor, and understand what each component does, how to use it, and how to customize it. Solution Unity’s user interface is organized along windows of content. Each different view can do different things. In this recipe, we’ll present some of the most important ones and talk about how to arrange the editor to suit your needs. When you launch Unity and create a new project, you’ll be taken to the editor’s main window (Figure 1-1).
Figure 1-1. The main window of the Unity editor. TIP When it’s first launched, Unity uses the layout that you see in Figure 1-1. However, you can resize any window by clicking and dragging on its edges. You can also reposition the window by clicking and dragging its tab to somewhere else. If you drag a tab to the edge of another window, it will be placed at that side of the window. If you drag a tab onto the middle of the window, it will be added to the list of tabs at the top of the window. There are several features that are of particular importance to anyone working in Unity. Let’s take a look at each of them! TOOLBAR The toolbar contains controls that affect Unity as a whole (Figure 1-2). It’s always at the top of the editor window, and can’t be moved. Figure 1-2. The toolbar. The toolbar, from left to right, contains the following controls: • Tools palette: This palette controls how the transform controls, which appear when an object is selected, behave. Only one mode can be selected at a time; they are: • Hand tool: Clicking and dragging in the Scene view will move your view of the scene.
• Move tool: Objects that are selected can be moved. • Rotate tool: Objects that are selected can be rotated around their pivot point or center. • Scale tool: Objects that are selected can be scaled around their pivot point or center. • Rectangle tool: Objects that are selected have a rectangle drawn around them, and can be scaled and repositioned. This tool is largely used for 2D objects like sprites and user interface elements. • Transform tool: This tool combines the Move, Rotate, and Scale tools. Selected objects can be moved, rotated, and scaled. • Pivot/Center toggle: This toggle sets whether the transform controls are placed at the local pivot point of the object or in the center of the object’s volume. (This can be different for certain 3D models; for example, models of human characters typically place the pivot point at the character’s feet.) • Local/Global toggle: This toggle sets whether the Transform tool operates in global space, or local space. For example, in local space, dragging the blue “forward” arrow of the Move tool moves an object forward based on its own orientation, while in global mode, dragging the same arrow ignores the object’s orientation. • Play button: This button starts Play mode, which enters your game. You can click the button again to end Play mode and return to editing. WARNING You can edit the scene while in Play mode, but any changes you make to the scene will be lost when you end the game. Don’t forget to check if you’re playing the game or not before doing a large amount of work! • Pause button: This button pauses the game. If you’re in Play mode, the game will pause immediately. If you’re not in Play mode, you can still click this button; if you then click the Play button, the game will pause immediately after the first frame. • Step button: This button advances one frame, while keeping the game paused. NOTE To be more specific, stepping forward “one frame” means that Unity will advance the game’s clock by the fixed timestep and then re-render the game. By default, the fixed timestep is 0.02 seconds; you can configure this in the project’s Time settings (from the Edit menu, choose Project Settings → Time). • Collab menu: This meno provides controls for working with Unity Collaborate, Unity’s version control service. NOTE Unity Collaborate is outside the scope of this book, but the Unity manual provides a good introduction. • Services button: This button opens the Services view, which allows you to work with Unity’s web-based services like Cloud Build, Unity Analytics, and more. For more information, see Unity’s Services page.
• Account button: This button allows you to configure your Unity account. • Layers button: With this button you can choose which layers are currently visible or selectable. • Layout button: This button allows you to save and restore a predefined layout of windows. This is useful when you have a layout that works well for tasks like animation, or level layout, and you want to switch between different tasks without having to fiddle with precise window placement. SCENE The Scene view allows you to view, select, and modify the objects in a scene (Figure 1-3). Figure 1-3. The Scene view. In the Scene view, you can left-click on any object to select it; when an object is selected, you can move, rotate, or scale it by using the transform controls, depending on which tool you have selected in the toolbar (see Figure 1-4).
Figure 1-4. The Transform tool, shown when an object is selected. In this image, a Camera has been selected, and the Transform tool is in Move mode; clicking and dragging the arrows will move the selected object in that direction. To use the transform controls on a selected object, click and drag the arrows (when using the Move tool), circles (the Rotate tool), or boxes (Scale tool) attached to it. Hold down the Shift key to snap the movement, rotate, and scale to a predefined increment. To move around the Scene view, select the Hand tool from the palette at the top left of the view, and click and drag. You can also hold the Alt key (Option on a Mac) key to make clicking and dragging rotate the view; Alt-Control (Option-Command) and drag will pan the view around. You can use the scroll wheel on your mouse, or a two-finger gesture on a trackpad, to zoom in and out. TIP You can also quickly move the Scene view to focus on the currently selected object. To do this, press the F key. GAME The Game view displays the view through the camera, and shows what the player would see if the game were running outside of Unity (Figure 1-5). The Game view itself isn’t interactive unless the editor is in Play mode.
Figure 1-5. The Game view. There are a few controls at the top of the Game view that let you control how the game is presented. • The Display menu lets you control which display’s contents to show in the view. (In Unity, a camera can be configured to send its results to the main screen, or to an external screen.) • The Resolution menu lets you specify an aspect ratio or fixed resolution for the game display. • The Scale slider lets you zoom in on the rendered view of the game. • The Maximize On Play toggle button, when selected, makes the Game view fill the entire editor window when the game enters Play mode.
• The Mute Audio toggle button disables all audio playback from the game. (This is useful when you don’t want the game’s audio to play over the top of your music while you’re working, for example.) • The Stats toggle button controls whether performance statistics will be displayed in an overlay panel. • The Gizmos button lets you control whether the gizmos—icons that represent certain objects in the scene, like cameras—appear in the Game view, like they do in Scene view. INSPECTOR The Inspector shows information about the objects that are currently selected (Figure 1-6). From here, you can control every component that’s attached to the game object.
(This page has no text content)
Figure 1-6. The Inspector. NOTE Components are a huge part of how Unity works, which means we’ll discuss them in Recipe 1.3, instead of here. At the top of the Inspector, you can set the name of the currently selected object. You can also set an icon for the object by clicking on the icon to the left of the object’s name and choosing a symbol to use. This is useful for game objects that are invisible. By default, the Inspector will change its contents when the current selection changes. If you don’t want it to do this, you can click the Lock icon at the top-right corner of the Inspector, and it will stay on the object that it’s currently displaying. HIERARCHY The Hierarchy shows the list of objects in the current scene (Figure 1-7). From here, you can browse through the list of objects in your scene. If you select an item in the Hierarchy, it becomes selected in the Scene view, and vice versa. You can also drag and drop one object on another in order to make it a child of that second object.
Figure 1-7. The Hierarchy view. PROJECT The Project view shows the contents of the project’s Assets folder (Figure 1-8). Any files that are in the folder will be visible here; you can also move and rename files.
WARNING If you want to rename a file, do it inside the Project view, and not outside of Unity. Unity keeps track of the additional metadata about your assets, such as import settings for textures, by creating a new file with the extension .meta next to each asset file. For example, an asset file called Hero.png would have a file called Hero.png.meta placed next to it. If you rename, move or delete the asset file inside Unity, Unity will also update the .meta file, but if you rename, move, or delete the asset file outside of Unity, it won’t know what to do, and it will have to recreate the .meta file from scratch (which means that any references to the file are lost, as well as any import settings). Figure 1-8. The Project view. Discussion You can right-click on the menu at the top bar of any window to close it. If you’ve closed a window and you want to get it back, you can usually find it in the Window menu. If you’re really stuck, open the Window menu and choose Layouts → Revert Factory Settings. 1.2 Working with Game Objects Problem You want to create and modify game objects, which populate your game’s scenes. Solution To create a new, empty game object, open the GameObject menu, and choose Create Empty. A new, empty game object will be added to the scene. It won’t be visible in the scene, because it won’t have any components that render anything. To learn more about components, see Recipe 1.3.
TIP You can also press Command-Shift-N (Control-Shift-N on a PC) to create a new, empty game object. You can rename a game object by selecting it, and changing its name in the Inspector. Game objects can be the child of other game objects. When a game object moves, rotates, or scales, its children are affected as well. This means that you can create hierarchies of game objects that work together as a system; for example, a car could have each of its four wheels as child objects, which means that they automatically stay in the correct position as the car moves around. To make one game object the child of another, drag and drop it onto another object in the Hierarchy (see “Hierarchy”). You can also reorder a object by dragging and dropping it in the Hierarchy. As a shortcut, you can make an object move to the end of its siblings by pressing Command-Equals (Control-Equals on PC), and move to the start of its siblings by pressing Command-Minus (Control-Minus on PC). Discussion You can also create new game objects by dragging and dropping assets into the Scene view. For example, if you drag and drop a 3D model asset into the Scene view, Unity will create a new game object that contains the necessary components for rendering that model. As a shortcut, you can quickly create an empty game object as a child of the currently selected object by opening the GameObject menu and choosing Create Empty Child. You can also press Option-Shift-N (Alt-Shift-N on a PC). 1.3 Working with Components Problem You want to add and modify components, which control the appearance and behavior of your game objects. Solution On its own, a game object is just an empty container. It’s the components that make a game object actually do anything useful. To get started in thinking about components, we’ll create a new game object that comes with some useful components built in: we’ll add a cube to the scene! To do this, follow these steps: 1. Open the GameObject menu, and choose 3D Object → Cube. A new cube will be added to the scene (Figure 1-9). 2. Select the new cube in the Hierarchy or the Scene view. The Inspector will update to show the list of components attached to it (Figure 1-10).
(This page has no text content)
Figure 1-9. A new cube, freshly added to the scene.
(This page has no text content)