Hands-On Unity 2022 Game Development - Nicolas Alejandro Borromeo - E-Book

Hands-On Unity 2022 Game Development E-Book

Nicolas Alejandro Borromeo

0,0
32,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Unity is a cross-platform game engine that provides you with powerful but simple-to-use features to solve the most common problems in Game Development, such as rendering, animation, physics, sound, and effects. You’ll learn to use these features to create simple but complete games (and all the nuances needed to handle Unity).

Complete with hands-on tutorials and projects, this book will teach you to use the Unity game engine, create C# and visual scripts, integrate graphics, sound, and animations, and manipulate physics to create interesting mechanics for your game. You’ll then code a simple AI agent to challenge the user and work with profiling tools to ensure code efficiency.

Finally, you'll work with Unity's AR tools to create AR experiences for 3D apps and games before publishing them to the world.

If you are interested in creating impressive, commercial-quality games that are playable on a variety of platforms, then you’ve come to the right place.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 747

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Hands-On Unity 2022 Game Development

Third Edition

Learn to use the latest Unity 2022 features to create your first video game in the simplest way possible

Nicolas Alejandro Borromeo

BIRMINGHAM—MUMBAI

Hands-On Unity 2022 Game Development

Third Edition

Copyright © 2022 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, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Manish Nainani

Acquisition Editor – Peer Reviews: Gaurav Gavas

Project Editor: Amisha Vathare

Content Development Editor: Grey Murtagh

Copy Editor: Safis Editing

Technical Editor: Srishty Bhardwaj

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Presentation Designer: Pranit Padwal

First published: July 2020

Second edition: August 2021

Third edition: October 2022

Production reference: 1211022

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-691-9

www.packt.com

Contributors

About the author

Nicolas Alejandro Borromeo is a Game Developer currently working for Unity Technologies as a Senior Software Development Consultant and Unity Certified Instructor in London, helping Unity clients with their projects all around the globe. He started using Unity in 2008 and teaching it in 2012 at several universities and educational institutions.

I want to say thanks to my father who always encouraged my love for computers and games; I miss you. Also to my wife Edith, for always reminding me what I’m capable of, and supporting me in my career.

About the reviewer

Rafael J. M. Ocariz is currently an Expert Software Engineer living in Quebec City, Canada. With 11 years of experience in software development, 8 of those developing games in Unity, he has developed products for mobile, PC, and VR platforms. His portfolio includes big titles from the Call of Duty franchise, Crash Bandicoot, Tony Hawk’s, and WWE. He also has solid skills in several other technologies, such as distributed systems, modern C++, Unreal Engine, Lua, Python, and native app development for Android and iOS.

I’d like to thank God and my wife, Giovanna N. Barbero, for all the support they gave me during this project.

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Share your thoughts

Creating a Unity Project

Installing Unity

Unity’s technical requirements

Unity versioning

Installing Unity with Unity Hub

Creating projects

Creating a project

Project structure

Summary

Editing Scenes and Game Objects

Manipulating scenes

The purpose of a scene

The Scene View

Adding our first GameObject to the scene

Navigating the Scene View

Manipulating GameObjects

GameObjects and components

Understanding components

Manipulating components

Object Hierarchies

Parenting of objects

Possible uses

Prefabs

Creating Prefabs

Prefab-instance relationship

Prefab variants

Saving scenes and projects

Summary

Grayboxing with Terrain and ProBuilder

Defining our game concept

Creating a landscape with Terrain

Discussing Height Maps

Creating and configuring Height Maps

Authoring Height Maps

Adding Height Map details

Creating shapes with ProBuilder

Installing ProBuilder

Creating a shape

Manipulating the mesh

Adding details

Summary

Importing and Integrating Assets

Importing assets

Importing assets from the internet

Importing assets from the Asset Store

Importing assets from Unity Packages

Integrating assets

Integrating terrain textures

Integrating meshes

Integrating textures

Configuring assets

Configuring meshes

Configuring textures

Assembling the scene

Summary

Introduction to C# and Visual Scripting

Creating scripts

Initial setup

Creating a C# script

Adding fields

Creating a Visual Script

Using events and instructions

Events and instructions in C#

Events and instructions in Visual Scripting

Using fields in instructions

Common beginner C# script errors

Summary

Implementing Movement and Spawning

Implementing movement

Moving objects through Transform

Using Input

Understanding Delta Time

Implementing spawning

Spawning objects

Timing actions

Destroying objects

Using the new Input System

Installing the new Input System

Creating Input Mappings

Using Mappings in our scripts

Summary

Physics Collisions and Health System

Configuring physics

Setting shapes

Physics object types

Filtering collisions

Detecting collisions

Detecting Trigger events

Modifying the other object

Moving with physics

Applying forces

Tweaking physics

Summary

Win and Lose Conditions

Creating object managers

Sharing variables with the Singleton design pattern

Sharing variables with Visual Scripting

Creating managers

Creating Game Modes

Improving our code with events

Summary

Implementing Game AI for Building Enemies

Gathering information with sensors

Creating three-filter sensors with C#

Creating Three-Filters sensors with Visual Scripting

Debugging with gizmos

Making decisions with FSMs

Creating the FSM in C#

Creating transitions

Creating the FSM in Visual Scripting

Executing FSM actions

Calculating our scene’s NavMesh

Using Pathfinding

Adding the final details

Summary

Materials and Effects with URP and Shader Graph

Introducing shaders and URP

Shader Pipeline

Render Pipeline and URP

URP built-in shaders

Creating shaders with Shader Graph

Creating our first Shader Graph

Using Textures

Combining Textures

Applying transparency

Creating Vertex Effects

Summary

Visual Effects with Particle Systems and Visual Effect Graph

Introduction to Shuriken particle systems

Creating a basic particle system with Shuriken

Using advanced modules

Creating fluid simulations

Creating a waterfall effect

Creating a bonfire effect

Creating complex simulations with Visual Effect Graph

Installing Visual Effect Graph

Creating and analyzing a Visual Effect Graph

Creating a rain effect

Scripting Visual Effects

Summary

Lighting Using the Universal Render Pipeline

Applying lighting

Discussing lighting methods

Configuring ambient lighting with skyboxes

Configuring lighting in URP

Applying shadows

Understanding shadow calculations

Configuring performant shadows

Optimizing lighting

Understanding static lighting

Baking lightmaps

Applying static lighting to static objects

Summary

Full-Screen Effects with Post-Processing

Using post-processing

Setting up a profile

Using basic effects

Using advanced effects

High Dynamic Range (HDR) and Depth Map

Applying advanced effects

Summary

Sound and Music Integration

Importing audio

Audio types

Configuring import settings

Integrating and mixing audio

Using 2D and 3D AudioSources

Using an Audio Mixer

Scripting audio feedback

Summary

User Interface Design

Understanding the Canvas and RectTransform

Creating a UI with the Canvas

Positioning elements with RectTransform

Canvas object types

Integrating assets for the UI

Creating UI controls

Creating a responsive UI

Adapting object positions

Adapting object sizes

Scripting the UI

Showing information in the UI

Programming the Pause menu

Summary

Creating a UI with the UI Toolkit

Why learn UI Toolkit?

Creating a UI with UI Toolkit

Creating UI Documents

Editing UI Documents

Creating UI Stylesheets

Making a responsive UI

Dynamic positioning and sizing

Dynamic scaling

Using relative positions

Summary

Creating Animations with Animator, Cinemachine, and Timeline

Using Skinning Animation with Animator

Understanding skinning

Importing skeletal animations

Integration using Animation Controllers

Using Avatar Masks

Scripting animations

Scripting player shooting animations

Scripting movement animations

Creating dynamic cameras with Cinemachine

Creating camera behaviors

Creating dolly tracks

Creating cutscenes with Timeline

Creating animation clips

Sequencing our intro cutscene

Summary

Optimization with Profiler, Frame Debugger, and Memory Profiler

Optimizing graphics

Introduction to graphics engines

Using Frame Debugger

Using batching

Other optimizations

Optimizing processing

Detecting CPU- and GPU-bound

Using the CPU Usage Profiler

General CPU optimization techniques

Optimizing memory

Memory allocation and the garbage collector

Using the Memory Profiler

Summary

Generating and Debugging an Executable

Building a project

Debugging the build

Debugging code

Profiling performance

Summary

Augmented Reality in Unity

Using AR Foundation

Creating an AR Foundation project

Using tracking features

Building for mobile devices

Building for Android

Building for iOS

Creating a simple AR game

Spawning the player and enemies

Coding the player and enemy behavior

Summary

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Preface

I still remember that moment of my life when I was afraid of telling my parents that I was going to study game development. At that time, in my region, that was considered a childish desire by most parents, and a career with no future, but I was stubborn enough not to care and to follow my dream. Today, game development is one of the biggest industries, generating more revenue than film.

Of course, following my dream was more difficult than I thought. Anyone with the same dream as me sooner or later faces the fact that developing games is a difficult task that requires a deep level of knowledge in different areas. Sadly, most people give up due to this difficulty level, but I strongly believe that with the proper guidance and tools, you can make your career path easier. In my case, what helped me to flatten the learning curve was learning to use Unity.

Welcome to this book about Unity 2022. Here, you will learn how to use the most recent Unity features to create your first videogame in the simplest way possible nowadays. Unity is a tool that provides you with powerful but simple-to-use features to solve the most common problems in game development, such as rendering, animation, physics, sound, and effects. We will be using all these features to create a simple but complete game, learning all the nuances needed to handle Unity.

If you have read the 2021 edition of this book, you will find that not only have the contents been updated to the latest Unity and Packages versions, but also new content has been introduced in 2022, such as coverage of the new Input System.

By the end of this book, you will be able to use Unity in a way that will allow you to start studying in depth the areas of game development that you are interested in to build your career or simply create hobby games just for the joy of doing it. Unity is a versatile tool that can be used in both professional and amateur projects, and is being used every day by more and more people.

It is worth mentioning that Unity can be used not only for creating games but for any kind of interactive apps, from simple mobile apps to complex training or educative applications (known as Serious Gaming), using the latest technologies such as Augmented or Virtual Reality. So, even if we are creating a game here, you are starting a learning path that can end in lots of possible specializations.

Who this book is for

People with different backgrounds can take advantage of the whole book or parts of it thanks to the way it is structured. If you have basic OOP knowledge but have never created a game before, or have never created one in Unity, you will find the book a nice introduction to game development and Unity basic to advanced concepts. You could also find most parts of this book useful even if you are a seasoned Unity developer who wants to learn how to use its latest features.

On the other side, if you don’t have any programming knowledge, you can also take advantage of the book, as most of the chapters don’t require programming experience to learn from them. Those chapters will give you a robust skillset to start learning coding in Unity, making the process easier than before reading them, and once you learn the basics of coding, you can take advantage of the scripting chapters of this book. Also, with the introduction of Visual Scripting, you will have an alternative language if you are more comfortable with node-based scripting.

What this book covers

Chapter 1, Creating a Unity Project, teaches you how to install and set up Unity on your computer, and also how to create your first project.

Chapter 2, Editing Scenes and GameObjects, teaches you the concepts of Scenes and GameObjects, the Unity way to describe what your game world is composed of.

Chapter 3, Working with Scenes and Game Objects, is where we will be creating our first level layout, prototyping it with the Terrain and ProBuilder Unity features.

Chapter 4, Importing and Integrating Assets, is where we will be creating our first level layout, prototyping it with the Terrain and ProBuilder Unity features.

Chapter 5, Introduction to C# and Visual Scripting, is the first programming chapter of the book. We will learn how to create our first script using C# in the Unity way, and then we will explore how to do the same with Visual Scripting, the new node-based coding language of Unity. The rest of the programming chapters will show how to code the game in both languages.

Chapter 6, Implementing Movement and Spawning, teaches you how to program the movement of your objects and how to spawn them. This chapter introduces the new Unity Input System. General programming knowledge is assumed from now on.

Chapter 7, Physics Collisions and Health System, teaches you how to configure the Physics settings of objects to detect when two of them collide and react to the collision, creating a health system, in this case.

Chapter 8, Win and Lose Condition, covers how to detect when the game should end, both when the player wins and loses.

Chapter 9, Implementing Game AI for Building Enemies, covers creating a basic AI using several Unity features for creating challenging enemies in our game.

Chapter 10, Materials and Effects with URP and Shader Graph, shows how to use one of the latest Unity render systems (Universal Render Pipeline, or URP) and how to create effects with the Shader Graph feature.

Chapter 11, Visual Effects with Particle Systems and Visual Effect Graph, teaches you how to create visual effects such as water and fire using the two main Unity tools for doing so, Particle Systems and VFX Graph, and how to make scripts that control them according to what’s happening in the game.

Chapter 12, Lighting Using the Univeral Render Pipeline, looks at lighting, which is a concept big enough to have its own chapter. Here, we will deepen our knowledge of the Universal Render Pipeline, specifically its lighting capabilities.

Chapter 13, Fullscreen Effects with Postprocessing, teaches you how to add a layer of effects on top of your scene graphics using the postprocessing feature of the Universal Render Pipeline to get that film effect most modern games have today.

Chapter 14, Sound and Music Integration, covers a topic that is underestimated by most beginner developers; here we will learn how to properly add sound and music to our game, taking into consideration its impact on performance. This also covers how to script the sound.

Chapter 15, User Interface Design, looks at the User Interface (UI). Of all the graphical ways to communicate information to the user, the UI is the most direct one. We will learn how to display information in the form of text, images, and life bars using the Unity UI system, and also how to script the UI.

Chapter 16, Creating a UI with the UI Toolkit, looks at UI Toolkit, which is the successor of Canvas, the UI system we learned about in Chapter 15, User Interface Design. We will explore it to get ahead and be prepared for Unity’s use of this HTML-based toolkit in the future.

Chapter 17, Creating Animations with Animator, Cinemachine, and Timeline, takes us further than the static scene we have created so far. In this chapter, we will start moving our characters and creating cutscenes with the latest Unity features to do so, and how to script them.

Chapter 18, Scene Performance Optimization, discusses how making our game perform well is no easy task, but is certainly needed to release it. Here, we will be learning how to profile our game’s performance and tackle the most common performance issues.

Chapter 19, Building the Project, teaches you how to convert your Unity project into an executable format to distribute it to other people and run it without Unity installed.

Chapter 20, Augmented Reality in Unity, teaches you how to create an AR application with Unity’s AR Foundation package, one of the most recent ways to create AR applications with Unity.

To get the most out of this book

You will be developing a full project through the chapters of this book, and while you can just read the chapters, I highly recommend you practice all the steps in this project as you advance through the book, to get the experience needed to properly learn the concepts demonstrated here. The chapters are designed so you can customize the game and not create the exact game shown in the book. However, consider not deviating too much from the main idea.

The project files are split into a folder per chapter and are designed in a cumulative way, each folder having just the new files introduced by the chapter or the changed ones. This means, for example, that if a file hasn’t change since Chapter 1, you won’t find it in Chapter 2 onward; those chapters will just use the file introduced in Chapter 1. This allows you to see just what we changed in each chapter, easily identifying the needed changes, and if for some reason you can’t finish, for example, Chapter 3, you can just continue with Chapter 4’s steps on top of Chapter 3. Also note that Chapters 15 to 19 will have two versions of the files, the C# ones and the Visual Scripting ones.

Software/hardware covered in the book

OS requirements

Unity 2022.1

Windows, macOS X or Linux (any)

Visual Studio 2022 Community

Windows or macOS X (any)

XCode 13

macOS X

While we will see how to use XCode 13, is not required for most of the chapters. Also, there are alternatives to Visual Studio in Linux, like Visual Studio Code.

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

The code bundle for the book is hosted on GitHub at https://github.com/PacktPublishing/Hands-On-Unity-2022-Game-Development-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803236919_ColorImages.pdf .

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example: “Set its shader to Universal Render Pipeline/Particles/Unlit.”

Bold: Indicates a new term, an important word, or words that you see on the screen. For instance, words in menus or dialog boxes appear in the text like this. For example: “Create a new empty GameObject (GameObject | Create Empty).”

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Share your thoughts

Once you’ve read Hands-On Unity 2022 Game Development, Third Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781803236919

Submit your proof of purchase That’s it! We’ll send your free PDF and other benefits to your email directly

1

Creating a Unity Project

In this chapter, we will learn how to install Unity and create a project with Unity Hub, a tool that manages different Unity installations and projects, among other tasks. Unity Hub gives easy access to community blogs, forums, resources, and learning portals; it also manages your licenses, and allows you to change the building platform before opening the project on top of managing different installs and projects.

Specifically, we will examine the following concepts in this chapter:

Installing UnityCreating projects

Let’s start by talking about how to get Unity up and running.

Installing Unity

We’ll begin with a simple but necessary first step: installing Unity. It seems like a straightforward first step, but we can discuss the proper ways to do this. In this section, we will be looking at the following concepts:

Unity’s technical requirementsUnity versioningInstalling Unity with Unity Hub

First, we will discuss what is necessary to run Unity on our computers.

Unity’s technical requirements

To run Unity 2022, your computer will need to meet the following operating system requirements:

If you use Windows, you need Windows 7 Service Pack 1 or greater, Windows 10, or Windows 11. Unity will run only on 64-bit versions of those systems; there is no 32-bit support unless you are willing to work with Unity versions before 2017.x, but that’s outside the scope of this book.For Mac, you need Big Sur 11.0 to run Apple silicon versions of the editor. In any other case, you can run Intel versions of the editor from High Sierra 10.13 or superior.For Linux, you need exactly Ubuntu 20.04, 18.04, or CentOS 7.

Regarding the CPU, these are the requirements:

Your CPU needs to support 64 bitsYour CPU needs to support SSE2 (most CPUs support it)In the case of Macs with Apple silicon, M1 or above is needed

Finally, regarding graphics cards, these are the supported ones:

On Windows, we need a graphics card with DirectX 10, 11, or 12 support (most modern GPUs support it)On Mac, any Metal-capable Intel or AMD GPU will be enoughOn Linux, OpenGL 3.2 or any superior version, or a Vulkan-compatible card from Nvidia and AMD is supported

Now that we know the requirements, let’s discuss the Unity installation management system.

Unity versioning

Unity releases a new major version each year—at the time of writing, 2022.1—and during that year it receives an update with new features, which is planned to be 2022.2 at the time of writing this book. Near the end of the year or during the beginning of the next one, an LTS (long-term support) version is released, which will be 2022.3 for this edition of the book, marking the end of new features being added to that year’s version of the engine. After that, the next year’s edition of the engine is released, and the cycle repeats.

LTS versions have the benefit that they are planned to be updated bi-weekly with bug fixes for 2 years, while new major versions of Unity release. That’s the reason most companies stick to LTS versions of the engine: because of its stability and long-term support. In this book we will be using 2022.1 just to explore the new features of the engine, but consider sticking to LTS versions when developing commercial game titles.

Considering this, you may need to have several versions of Unity installed in case you work on different projects made with different versions. You may be wondering why you can’t just use the latest version of Unity for every project, but there are some problems with that.

In newer versions of Unity, there are usually lots of changes to how the engine works, so you may need to rework lots of pieces of the game to upgrade it, including third-party plugins. It can take lots of time to upgrade the whole project, and that can push the release date back. Maybe you need a specific feature that comes with an update that will help you. In such a case, the cost of upgrading may be worthwhile. For projects that are maintained and updated for several years, developers are used to updates only to the latest LTS versions of the editor, although this policy may vary from case to case.

Managing different projects made with different Unity versions, and installing and updating new Unity releases, all used to be a huge hassle. Thus, Unity Hub was created to help us with this, and it has become the default way to install Unity. Despite this, it is not necessary for installing Unity, but we will keep things simple for now and use it. Let’s look closer into it.

Installing Unity with Unity Hub

Unity Hub is a small piece of software that we will install before installing Unity. It centralizes the management of all your Unity projects and installations. You can get it from the official Unity website. The steps to download it change frequently, but at the time of writing this book, you need to do the following:

Go to unity.com.Click on the Get started button, as shown in the following screenshot:

Figure 1.1: The Get started button on Unity’s website

Click on the Student and hobbyist tab; then, under the Personal section, click on the Get started button, as illustrated in the following screenshot:

Figure 1.2: Choosing an individual/free license

Scroll down to the section saying 1. Download the Unity Hub and click on the Download button according to your operating system. For Windows, click Download for Windows, and for Mac, click on Download for Mac. For Linux, there is an Instructions for Linux button with further info about how to install on that platform, but we won’t be covering Unity in Linux in this book:

Figure 1.3: Starting the download

Execute the downloaded installer.Follow the instructions of the installer, which will mostly be clicking Next all the way to the end.

Now that we have Unity Hub installed, we must use it to install a specific Unity version. You can do this with the following steps:

Start Unity Hub.If prompted to install a Unity version and/or create a license, please skip these steps with the corresponding Skip buttons (which may vary according to the Unity Hub version). This way to install Unity and licenses is only available the first time you run Unity Hub, but we are going to learn the way to do this that works after the first time.Log in to your account by clicking on the “person” icon at the top-left part of the window and selecting Sign in:

Figure 1.4: Signing into Unity Hub

Here, you also have the option to create a Unity account if you haven’t already, as illustrated in the link labeled create one that appears in the Unity login prompt in the following screenshot:

Figure 1.5: Logging into Unity Hub

Follow the steps on the installer and then you should see a screen like the one in the next image. If it is not the same, try clicking the Learn button at the top-left part of the screen:

Figure 1.6: The Unity Hub window

Click on the Installs button and check if you have Unity 2022 listed there. If not, press the Install Editor button at the top-right corner. This will show a list of Unity versions that can be installed from here:

Figure 1.7: Unity versions available to install

You will see three tabs here. Official releases contains the latest versions of each major release already released. Pre-releases contains alpha and beta releases of Unity, so you can participate in these programs and test new features before they are officially released. Archive contains a link to the Unity Download Archive that contains every single Unity version released. For example, the official release at the moment of writing this is 2022.1.20, but the project is being developed in 2022.1.14, so you can install the correct version from the archive.Locate Unity 2022.1 in the Official releases tab.Click on the Install button at the right of Unity 2022.1.XXf1, where XX will vary according to the latest available version. At the moment of writing this book we are using 2022.1.14f1. You might need to scroll down to find this version. If not present, install the latest 2022 version available (for example, 2022.2.XX or 2022.3.XX). Newer versions might vary of what is seen in the book, if you find the images of the book being too different consider looking for Unity 2022.1.14 in the archive.A modules selection window will show up. Make sure the Visual Studio feature is checked. While this program is not needed to work in Unity, we will be using it later in the book. If you already have a C# IDE installed, feel free to skip it.Now, click the Continue button:

Figure 1.8: Selecting Visual Studio

Accept Visual Studio’s terms and conditions and then click Install:

Figure 1.9: Accepting Visual Studio’s terms and conditions

It is important to note that Visual Studio is the program we will use in Chapter 5,Introduction to Scripting with C# and Visual Scripting, to create our code. We do not need the other Unity features right now, but you can go back later and install them if you need them.

You will see the selected Unity version downloading and installing. Wait for this to finish. If you don’t see it, click the Downloads button to reopen it:

Figure 1.10: Currently active Unity Hub downloads

If you decided to install Visual Studio, after Unity has finished installing, the Visual Studio Installer will automatically execute. It will download an installer that will download and install Visual Studio Community:

Figure 1.11: Installing Visual Studio

To confirm everything worked, you must see the selected Unity version in the list of Installs of Unity Hub:

Figure 1.12: Available Unity versions

Now, before using Unity, we need to acquire and install a free license to make it work by doing the following:

Click the Manage licenses button at the top-right corner of the Unity Hub. If you don’t see it, click your account icon at the top-left corner and click Manage licenses there:

Figure 1.13: The Manage licenses button to press in order to acquire a free license

Click the Add button in the Licenses list window:

Figure 1.14: The Licenses list window’s Add button

Click the Get a free personal license button:

Figure 1.15: Option to get a free personal license

Read and accept the terms and conditions if you agree with them by clicking the Agree and get personal edition license button:

Figure 1.16: The button to accept the terms and conditions

Remember that the preceding steps may be different in new Unity Hub versions, so just try to follow the flow that Unity designed—most of the time, it is intuitive.

Now it is time to create a project using Unity.

Creating projects

Now that we have Unity installed, we can start creating our game. To do so, we first need to create a project, which is basically a folder containing all the files that your game will be composed of. These files are called assets and there are different types of them, such as images, audio, 3D models, script files, and so on. In this section, we will see how to manage a project, addressing the following concepts:

Creating a projectProject structure

Let’s learn first how to create a blank project to start developing our project.

Creating a project

As with Unity installations, we will use the Unity Hub to manage projects. We need to follow these next steps to create one:

Open the Unity Hub and click on the Projects button, and then click on New project:

Figure 1.17: Creating a new project in Unity Hub

Pick the 3D (URP) template as we will be creating a 3D game with simple graphics, prepared to run on every device Unity can be executed on, so the Universal Render Pipeline (or URP) is the better choice for that. In Chapter 10, Materials and Effects with URP and Shader Graph, we will be discussing exactly why. If you see a Download template button, click it; if not, that means you already have the template:

Figure 1.18: Downloading the 3D URP template

Choose a Project name and a Location, and click Create project:

Figure 1.19: Selecting the Universal Render Pipeline template

Unity will create and automatically open the project. This can take a while, but after that you will see a window similar to the one in the following image. You might see the dark-themed editor instead, but for better clarity we will use the light theme throughout the book. Feel free to keep the dark theme:

Figure 1.20: The Unity Editor window

Close the window, then go back to Unity Hub and pick the project from the list to open it again:

Figure 1.21: Reopening the project

Now that we have created the project, let’s explore its structure.

Project structure

We have just opened Unity, but we won’t start using it until the next chapter. Now, it’s time to see how the project folder structure is composed. To do so, we need to open the folder in which we created the project. If you don’t remember where this is, you can do the following:

Right-click the Assets folder in the Project panel, located at the bottom part of the editor.Click the Show in Explorer option (if you are using a Mac, the option is called Reveal in Finder). The following screenshot illustrates this:

Figure 1.22: Opening the project folder in Explorer

Then, you will see a folder structure similar to this one (some files or folders may vary):

Figure 1.23: Unity project folder structure

If you want to move this project to another PC or send it to a colleague, you can just compress all those files and send it to them as a ZIP file, but not all the folders are necessary all of the time. The important folders are Assets, Packages, and ProjectSettings. Assets will hold all the files we will create and use for our game, so this is a must. We will also configure different Unity systems to tailor the engine to our game; all the settings related to this are in the ProjectSettings and UserSettings folders. Finally, we will install different Unity modules or packages to expand its functionality, so the Packages folder will hold which ones we are using.

It’s not necessary to copy the rest of the folders if you need to move the project elsewhere or add it to any versioning system, but let’s at least discuss what the Library folder is, especially considering it’s usually a huge size. Unity needs to convert the files we will use to its own format in order to operate, and an example would be audio and graphics. Unity supports MPEG Audio Layer 3 (MP3), Waveform Audio File Format (WAV), Portable Network Graphics (PNG), and Joint Photographic Experts Group (JPG) files (and much more), but prior to using them, they need to be converted to Unity’s internal formats, a process called Importing Assets. Those converted files will be in the Library folder. If you copy the project without that folder, Unity will simply take the original files in the Assets folder and recreate the Library folder entirely. This process can take time, and the bigger the project, the more time involved.

Keep in mind that you want to have all the folders Unity created while you are working on the project, so don’t delete any of them while you work on it, but if you need to move an entire project, you now know exactly what you need to take with you.

Summary

In this chapter, we reviewed how the Unity versioning system works. We also saw how to install and manage different Unity versions using Unity Hub. Finally, we created and managed multiple projects with the same tool. We will use Unity Hub a lot, so it is important to know how to use it initially. Now, we are prepared to dive into the Unity Editor.

In the next chapter, we will start learning the basic Unity tools to author our first level prototype.

Join us on Discord!

Read this book alongside other users, Unity game development experts, and the author himself.

Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/handsonunity22

2

Editing Scenes and Game Objects

In this chapter, we will develop some base knowledge of Unity in order to edit a project, and learn how to use several Unity editor windows to manipulate our first scene and its objects. We will also learn how an object, or GameObject, is created and composed, and how to manage complex scenes with multiple objects using Hierarchies and Prefabs. Finally, we will review how we can properly save all our work to continue working on it later.

Specifically, we will examine the following concepts in this chapter:

Manipulating scenesGameObjects and componentsObject HierarchiesPrefabsSaving scenes and projects

Manipulating scenes

A scene is one of the several types of files (also known as assets) in our project. A “scene” can be used for different things according to the type of project, but the most common use case is to separate your game into whole sections, the most common ones being the following:

Main menuLevel 1, Level 2, Level 3, etc.Victory screen and lose screenSplash screen and loading screen

In this section, we will cover the following concepts related to scenes:

The purpose of a sceneThe Scene ViewAdding our first GameObject to the sceneNavigating the Scene ViewManipulating GameObjects

So, let’s take a look at each of these concepts.

The purpose of a scene

The idea of separating your game into scenes is so that Unity can process and load just the data needed for the scene. Let’s say you are in the main menu; in such a case, you will have only the textures, music, and objects that the main menu needs loaded in random-access memory (RAM), the device’s main memory. In that case, there’s no need for your game to have loaded the Level 10 boss if you don’t need it right now. That’s why loading screens exist, just to fill the time between unloading the assets needed in one scene and loading the assets needed in another. Maybe you are thinking that open-world games such as Grand Theft Auto don’t have loading screens while you roam around in the world, but they are actually loading and unloading chunks of the world in the background as you move, and those chunks are different scenes that are designed to be connected to each other.

The difference between the Main Menu and a regular level scene is the objects (also known as GameObjects in the Unity lingo) they have. In a menu, you will find objects such as backgrounds, music, buttons, and logos, and in a level, you will have the player, enemies, platforms, health boxes, and so on. So, the meaning of your scene depends on what GameObjects are put into it. But how can we create a scene? Let’s start with the Scene View.

The Scene View

When you open a Unity project, you will see the Unity editor. It will be composed of several windows or panels, each one helping you to change different aspects of your game. In this chapter, we will be looking at the windows that help you create scenes. The Unity editor is shown in the following screenshot:

Figure 2.1: The Unity editor

If you have ever programmed any kind of application before, you are probably used to having a starting function such as Main, where you start writing code to create several objects needed for your app. If we are talking about games, you probably create all the objects for the scene there. The problem with this approach is that in order to ensure all objects are created properly, you will need to run the program to see the results, and if something is misplaced, you will need to manually change the coordinates of the object, which is a slow and painful process. Luckily, in Unity, we have the Scene View, an example of which is shown in the following screenshot:

Figure 2.2: The Scene View

This window is an implementation of the classic WYSIWYG (What You See Is What You Get) concept. Here, you can create objects and place them all over the scene, all through a scene previsualization where you can see how the scene will look when you hit Play. But before learning how to use this scene, we need to have an object in the scene, so let’s create our first object.

Adding our first GameObject to the scene

The project template we chose when creating the project comes with a blank scene ready to work with, but let’s create our own empty scene to see how to do it ourselves. To do that, you can simply use the File | New Scene menu to create an empty new scene, as illustrated in the following screenshot:

Figure 2.3: Creating a new scene

After clicking New Scene, you will see a window to pick a scene template; here, select the Basic (URP) template. A template defines which objects the new scene will have, and in this case, our template will come with a basic light and a camera, which will be useful for the scene we want to create. Once selected, just click the Create button:

Figure 2.4: Selecting the scene template

Now that we have our empty scene, let’s add GameObjects to it. We will learn several ways of creating GameObjects throughout the book, but for now, let’s start using some basic templates Unity provides us. In order to create them, we will need to open the GameObject menu at the top of the Unity window, and it will show us several template categories, such as 3D Object, 2D Object, Effects, and so on, as illustrated in the following screenshot:

Figure 2.5: Creating a cube

Under the 3D Object category, we will see several 3D primitives such as Cube, Sphere, Cylinder, and so on, and while using them is not as exciting as using beautiful, downloaded 3D models, remember that we are only prototyping our level at the moment. This is called gray-boxing, which means that we will use lots of prototyping primitive shapes to model our level so that we can quickly test it and see if our idea is good enough to start the complex work of converting it to a final version.

I recommend you pick the Cube object to start because it is a versatile shape that can represent lots of objects. So, now that we have a scene with an object to edit, the first thing we need to learn to do with the Scene View is to navigate through the scene.

Navigating the Scene View

In order to manipulate a scene, we need to learn how to move through it to view the results from different perspectives. There are several ways to navigate the scene, so let’s start with the most common one, the first-person view. This view allows you to move through the scene using a first-person-shooter-like navigation, using the mouse and the WASD keys. To navigate like this, you will need to press and hold the right mouse button, and while doing so, you can:

Move the mouse to rotate the camera around its current positionPress the WASD keys to move the position of the camera, always holding the right click You can also press Shift to move faster Press the Q and E keys to move up and down

Another common way of moving is to click an object to select it (the selected object will have an orange outline), and then press the F key to focus on it, making the Scene View camera immediately move into a position where we can look at that object more closely. After that, we can press and hold the left Altkey on Windows, or Option on Mac, along with the left mouse click, to finally start moving the mouse and “orbit” around the object. This will allow you to see the focused object from different angles to check every part of it is properly placed, as demonstrated in the following screenshot:

Figure 2.6: Selecting an object

Now that we can move freely through the scene, we can start using the Scene View to manipulate GameObjects.

Manipulating GameObjects

Another use of the Scene view is to manipulate the locations of the objects. In order to do so, we first need to select an object, and then press the Transform tool in the top-left corner of the Scene View. You can also press the Y key on the keyboard once an object is selected to do the same:

Figure 2.7: The transformation tool

This will show what is called the Transform gizmo over the selected object. A gizmo is a visual tool overlaid on top of the selected object, used to modify different aspects of it. In the case of the Transform Gizmo, it allows us to change the position, rotation, and scale of the object, as illustrated in Figure 2.8. Don’t worry if you don’t see the cube-shaped arrows outside the sphere—we will be enabling them in a moment:

Figure 2.8: The Transform gizmo

Let’s start translating the object, which is accomplished by dragging the red, green, and blue arrows inside the gizmo’s sphere. While you do this, the object will be moving along the selected axis. An interesting concept to explore here is the meaning of the colors of these arrows. If you pay attention to the top-right area of the Scene View, you will see an axis gizmo that serves as a reminder of those colors’ meaning, as illustrated in the following screenshot:

Figure 2.9: The axis gizmo

Computer graphics use the classic 3D Cartesian coordinate system to represent objects’ locations. The red color is associated with the x axis of the object, green with the y axis, and blue with the z axis.

But what does each axis mean? If you are used to another 3D authoring program, this can be different, but in Unity, the z axis represents the Forward Vector, which means that the arrow is pointing along the front of the object; the x axis is the Right Vector, and the y axis represents the Up Vector.

These directions are known as local coordinates, and that’s because every object can be rotated differently, meaning each object can be pointing its forward, up, and right vectors elsewhere according to its orientation. The local coordinates will make more sense when used later in the Object Hierarchies section of the chapter, so bear with me on that, but it’s worth discussing global coordinates now. The idea is to have a single origin point (the zero point) with a single set of forward, right, and up axes that are common across the scene. This way, when we say the object has a global position of 5,0,0, we know that we are referring to a position 5 meters along the global x-axis, starting from the global zero position. The global axes are the ones you see in the top-right axis gizmos previously mentioned.

In order to be sure that we are working with local coordinates, meaning we will move the object along its local axes, make sure the Local mode is activated in the Scene View, as shown in the following screenshot:

Figure 2.10: Switching pivot and local coordinates

If the right button says Global instead of Local, just click it and select Local from the dropdown options. By the way, try to keep the left button as Pivot. If it says Center, click and select Pivot. The pivot of the object is not necessarily its center, and that depends entirely on the 3D model we are using, where the author of it will specify where the object rotation center is located. For example, a car could have its pivot in the middle of its back wheels, so when we rotate, it will respect the real car’s rotation center. Editing based on the object’s pivot will simplify our understanding of how rotating via C# scripts will work later in Chapter 6, Implementing Movement and Spawning. Also, now that we have enabled Local coordinates, you should see the cube-shaped arrows seen in Figure 2.8; we will use them in a moment to scale the cube.

I know—we are editing a cube, so there is no clear front or right side, but when you work with real 3D models such as cars and characters, they will certainly have those sides, and they must be properly aligned with those axes. If by any chance in the future you import a car into Unity and the front of the car is pointing along the x axis, you will need to make that model aligned along the z axis because the code that we will create to move our object will rely on that convention (but let’s keep that for later).

Now, let’s use this Transform gizmo to rotate the object using the three colored circles around it. If you click and drag, for example, the red circle, you will rotate the object along the x axis. If you want to rotate the object horizontally, based on the color-coding we previously discussed, you will probably pick the x axis—the one that is used to move horizontally—but, sadly, that’s wrong. A good way to look at the rotation is like the accelerator of a motorcycle: you need to take it and roll it. If you rotate the x axis like this, you will rotate the object up and down. So, in order to rotate horizontally, you would need to use the green circle or the y axis. The process is illustrated in the following screenshot:

Figure 2.11: Rotating an object

Finally, we have scaling, and we have two ways to accomplish that, one of them being through the gray cube at the center of the Transform gizmo shown in Figure 2.8. This allows us to change the size of the object by clicking and dragging that cube. Now, as we want to prototype a simple level, sometimes we want to stretch the cube to create, for example, a column, or a flat floor, and here’s where the second way comes in.

If you click and drag the colored cubes in front of the translation arrows instead of the gray one in the center, you will see how our cube is stretched over those axes, allowing you to change the shape of the object. If you don’t see those cube-shaped arrows, remember to enable Local coordinates as stated earlier in this section.

The process to stretch is illustrated in the following screenshot:

Figure 2.12: Scaling an object

Remember you can also use the gray cube in the middle to scale all axes at the same time if desired, also known as uniform scaling, the same gray cube we had in the Transform gizmo.

Finally, something to consider here is that several objects can have the same scale values but have different sizes, given how they were originally designed. Scale is a multiplier we can apply to the original size of the object, so a building and a car both with scale 1 makes perfect sense; the relative size of one against the other seems correct. The main takeaway here is that scale is not size, but a way to multiply it.

Consider that scaling objects is usually a bad practice in many cases. In the final versions of your scene, you will use models with the proper size and scale, and they will be designed in a modular way so that you can plug them one next to the other. If you scale them, several bad things can happen, such as textures being stretched and becoming pixelated, and modules that no longer plug properly. There are some exceptions to this rule, such as placing lots of instances of the same tree in a forest and changing its scale slightly to simulate variation. Also, in the case of gray-boxing, it is perfectly fine to take cubes and change the scale to create floors, walls, ceilings, columns, and so on, because in the end, those cubes will be replaced with real 3D models.

Here’s a challenge! Create a room composed of a floor, three regular walls, and the fourth wall with a hole for a door (three cubes), and no need for a roof. In the next image you can see how it should look:

Figure 2.13: Room task finished

Now that we can edit an object’s location, let’s see how we can edit all its other aspects.

GameObjects and components

We talked about our project being composed of assets (the project’s files), and that a scene (which is a specific type of asset) is composed of GameObjects; so, how can we create an object? Through a composition of components.

In this section, we will cover the following concepts related to components:

Understanding componentsManipulating components

Let’s start by discussing what a component is.

Understanding components

A component is one of several pieces that make up a GameObject; each one is in charge of different features of the object. There are several components that Unity already includes that solve different tasks, such as playing a sound, rendering a mesh, applying physics, and so on; however, even though Unity has a large number of components, we will eventually need to create custom components sooner or later.

In the next image you can see what Unity shows us when we select a GameObject:

Figure 2.14: The Inspector panel

In the previous screenshot, we can see the Inspector panel. If we needed to guess what it does right now, we could say it shows all the properties of objects selected either via the Hierarchy or the Scene View, and allows us to configure those options to change the behavior of the object (i.e. the position and rotation, if it will project shadows or not, and so on). That is true, but we are missing a key element: those properties don’t belong to the object; they belong to the components of the object. We can see some titles in bold before a group of properties, such as Transform and Box Collider, and so on. Those are the components of the object.

In this case, our object has a Transform, a Mesh Filter, a Mesh Renderer, and a Box Collider component, so let’s review each one of those.

Transform just holds the position, rotation, and scale of the object, and by itself it does nothing—it’s just a point in our game—but as we add components to the object, that position starts to have more meaning. That’s because some components will interact with Transform and other components, each one affecting the other.

An example of that would be the case of Mesh Filter and Mesh Renderer, both of those being in charge of rendering a 3D model. Mesh Renderer will render the 3D model, also known as mesh, specified by the Mesh Filter in the position specified in the Transform component, so Mesh Renderer needs to get data from those other components and can’t work without them.

Another example would be the Box Collider. This represents the physics shape of the object, so when the physics calculates collisions between objects, it checks if that shape is colliding with other shapes based on the position specified in the Transform component.

We will explore rendering and physics later in the book, but the takeaway from this section is that a GameObject is a collection of components, each component adding a specific behavior to our object, and each one interacting with the others to accomplish the desired task. To further reinforce this, let’s see how we can convert a cube into a sphere that will fall due to gravity applied via physics.

Manipulating components

The tool to edit an object’s components is the Inspector. It not only allows us to change the properties of our components but also lets us add and remove components. In this case, we want to convert a cube to a sphere, so we need to change several aspects of those components.

We can start by changing the visual shape of the object, so we need to change the rendered model or mesh. The component that specifies the mesh to be rendered is the Mesh Filter component. If we look at it, we can see a Mesh property that says Cube