Unity 2022 by Example - Scott H. Cameron - E-Book

Unity 2022 by Example E-Book

Scott H. Cameron

0,0
35,99 €

-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 2022 by Example is a complete introduction to building games in Unity following a project-based approach. You’ll be introduced to the Unity game engine and the tools available for building and customizing a game exactly the way you want it, while maintaining a good code foundation to build upon.
Once you get to grips with the fundamentals of Unity game development, you'll start creating a 2D collection game and an adventure game, followed by a 3D first person shooter game. Next, you’ll explore advanced topics, such as using machine learning to create AI-based enemy behavior, virtual reality for extending the first-person game, and augmented reality for developing a farming simulation game in a real-world setting. The book will help you gain hands-on knowledge of these topics as you build projects using the latest game tool kits. You'll also learn how to commercialize your game by publishing it to a distribution platform and maintain and support it throughout its lifespan. As you progress, you’ll gain real-world knowledge and experience by taking your games from conceptual design to completion.
By the end of this Unity book, you’ll have strong foundational knowledge of how to structure a Unity project that is both maintainable and extensible for commercially released games.

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

EPUB
MOBI

Seitenzahl: 814

Veröffentlichungsjahr: 2024

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.



Unity 2022 by Example

A project-based guide to building 2D and 3D games, enhanced for AR, VR, and MR experiences

Scott H. Cameron

Unity 2022 by Example

Copyright © 2024 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.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Vaideeshwari Muralikrishnan

Book Project Manager: Sonam Pandey

Senior Editor: Anuradha Joglekar

Technical Editor: Reenish Kulshrestha

Copy Editor: Safis Editing

Proofreader: Anuradha Joglekar

Indexer: Manju Arasan

Production Designer: Vijay Kamble and Prafulla Nikalje

DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

Publication date: June 2024

Production reference: 1030524

Published by Packt Publishing Ltd.Grosvenor House 11 St Paul’s SquareBirmingham B3 1RB, UK

ISBN 978-1-80323-459-5

www.packtpub.com

To my luvluv Bheng, my little buddy “Arckie,” and my peanut gang, Yzhen, Zhyon, and Xhymn – I love you all dearly. Sincere thanks for all your loving support, encouragement, and inspiration.

– Daddy Scott

In memory of our beloved daughter, Zhyon, who loved to draw.

Foreword

There aren’t many industries that cost you nothing to enter, yet still have the potential to earn you millions of dollars in just a few years. Typically, you would start a career by earning an expensive tertiary diploma, then perhaps complete an unpaid internship, and then start in your chosen industry with an entry-level salary.

But of course, who really wants typical?

Game development is an entirely open industry. Literally anyone with a halfway-decent PC and a desire to experiment, learn, and iterate can develop a simple new game in a few weeks. Of course, the larger the game you wish to produce, the more time you’ll need to dedicate to its production. The point is that your success is only a question of your own time input, not whether you have an expensive degree or even any industry experience.

And by “you,” I mean you, the reader. In a very real sense, your path between dreamer and success story lies within these pages. The first step, you’ve already taken: deciding to use a game development engine, rather than create everything from scratch.

Unity was first released 20 years ago and so has become a mature, polished product. In the world of game engines, Unity’s user base is unmatched, in part because the full-featured engine is completely free for individuals and independent studios, and in part because it’s not difficult to develop a working familiarity and build up from there.

That’s exactly what this book does. In this hefty tome, Scott Cameron will take you step by step through the complete project-creation process, from installing the Unity Hub to lighting, even to machine learning, and finally to publishing your polished game on Steam, all painstakingly compiled by an expert on the Unity engine.

An award-winning graphic artist, Unity Certified Expert, and good friend of mine, Scott’s broad experience in software and game development spans three decades. Even as an experienced developer myself, Scott remains my go-to guy for any technical hurdle I might have in Unity. His methodical, no-nonsense approach to coding and design makes him the perfect author for an all-encompassing book such as this.

Through each chapter, Scott introduces new technical concepts exactly when the reader needs them. He provides enough context and tips to proceed, plus cross-references and online links if the reader wants to dive deeper into a particular topic.

Almost everyone on the planet has played some kind of digital game on console, PC, mobile, or VR. If you’ve played Pokémon Go, Beat Saber, Monument Valley, Among Us, Overcooked, or a host of other popular titles, then you have already experienced Unity as a consumer. Scott’s guidance in Unity 2022 By Example will lead you from a novice to a competent, confident game creator.

Global revenue for games is approaching US$400 billion, having long since eclipsed the combined global revenue of film and music, and it’s growing fast. There is room in the industry for you and the game that’s in your head right now. Get started reading and absorbing this book!

The rest is up to you.

Edward Falzon MBUS MINFTECH Unity-certified Expert Programmer, President, Pluck Games

Contributors

About the author

Scott H. Cameron has over 25 years of experience in information technology, software development, and design. He’s had the pleasure of crafting innovative solutions across diverse industries, from entertainment to manufacturing and financial services to architecture.

For the past decade, his latest adventure has immersed him in game development as a Unity Certified Expert Programmer, senior engineer team lead, and expert course mentor at Zenva Academy. Whether creating captivating VR experiences, making remarkable indie games, or revolutionizing foreign language learning through gamification, he’s driven by a love for pushing creative boundaries and sharing his experiences.

I wrote this book amid a global pandemic, a super typhoon, and the loss of our daughter. I couldn’t have done it without my wife’s unwavering strength and support and my children’s inspiration. Love ya!

Thanks to friends, Edward, Kendrick, Sean, and Alvin, for influencing and motivating me. My gratitude also goes to Nica and Miguel, the artists.

Lastly, I’m thankful to my exceptional partners at Packt, the technical reviewer, and everyone who helped me write this book.

About the reviewer

John Estes is a long-time user of the Unity game engine in his work toward gamification in healthcare. He has served as an expert adviser to Jintronix, a start-up company using Microsoft Kinect in Unity for rehabilitation gamification. He has also used his technical, artistic, and healthcare skills as a research manager in a university simulation lab focused on VR research in neurological rehabilitation. Today, John focuses on freelance work in real-time cinematography as well as designing and programming independent games and educational materials for vestibular rehabilitation in Unity.

Table of Contents

Preface

Part 1: Introduction to Unity

1

Foundational Knowledge of Unity 2022

Technical requirements

Unity Hub – Choosing the 2D URP template

Installing Unity Hub

Installing the Unity Editor – What version?

What is a render pipeline?

Creating a project

Getting to know the Unity Editor and installing packages

The Unity Package Manager

Introducing the GameObject – All about Transform and components

Adding GameObjects to the scene

The Transform component

Components

2D sprites with Sprite Creator – Understanding the Sprite Renderer and draw ordering

Creating a new scene

Creating a sprite using Sprite Creator

Navigating the scene View

Creating our player character

Using Manipulation Tools

Sprite Layers and Ordering

Game Design Document (GDD) – Introducing the 2D collection game

Summary

Image sources

Part 2: 2D Game Design

2

Creating a 2D Collection Game

Technical requirements

Creating a 2D, top-down game environment with Tilemap

Level design – Guiding the player

Creating Tile Palettes

Building the collection game environment with Tilemap

Making the level playable – Tilemap Collider 2D

Introduction to creating scripts in C# – IDE, SOLID principles, and design patterns

The IDE – Visual Studio Community 2022

The C# Language – Object-oriented programming (OOP)

SOLID principles

Design patterns

Coding a simple player controller with the new Input System

New Input System

Player controller script

Summary

3

Completing the Collection Game

Technical requirements

Using CM to follow the Player and playtesting

Creating a Player Prefab

Creating a 2D follow camera

Playtesting the level

Game mechanics and how to create with code (components)

What is a game mechanic?

Adding to our GDD

Collecting pickups

Hitting hazards

Introduction to uGUI, the timer, counting, and winning

Canvas

TextMesh Pro

Updating the pickup count

The Timer script

Winning the game

Summary

Part 3: 2D Game Design Continued

4

Creating a 2D Adventure Game

Technical requirements

Extending the GDD – Introducing the 2D adventure game

Importing assets to use with Sprite Shape – A different kind of 2D environment builder

Importing and preparing the artwork

Level and environment design – Guiding the player

Signposting

Creating platforms

Moving platforms and triggers – Creating a dynamic interactable environment

Moving a Sprite Shape platform with Splines

Triggering actions in the level

Adding polish to our environment to immerse the player and optimizing

Polishing the environment

Optimizing draw calls

Summary

5

Continuing the Adventure Game

Technical requirements

Setting up the player character with PSD Importer

Rigging the actor

Generating the sprite mesh geometry

Adjusting the bone influence

Editing sprite bone weights

Setting up inverse kinematics (IK)

Creating actor animations

Using an Input Action Map

Moving the player with a player controller script

Processing Player Input

Creating the PlayerController script

Physics materials

Animating the character with Mecanim

Transitioning animation states

Changing the animation state with code

Flipping the player character

Summary

6

Introduction to Object Pooling in Unity 2022

Technical requirements

The object pooling pattern

The Unity object pooling API

Creating a new object pool

Additional parameters affecting the object pool

A pooled player shooting model

Creating the pooled player shooting model

Implementing the pooled shooting model

Adding pooled shooting to the player character

Summary

7

Polishing the Player’s Actions and Enemy Behavior

Technical requirements

Polishing with Shader Graph and Trail Renderer

Enabling post-processing

Applying glow to the bullet with Shader Graph

Creating a new Shader Graph 2D material

Adding a 2D light to the player

Polishing is easy with Trail Renderer

Enemy Prefabs and variants – Configuring with SOs

Creating an enemy Prefab with configurations

Creating an enemy variant for alternate enemy types

Creating a Prefab Variant

Implementing basic enemy behavior using an FSM

State Model

A simple FSM pattern

Changing state behaviors

Summary

8

Extending the Adventure Game

Technical requirements

Health and inflicting damage

Health system

Interfaces required!

Taking damage – IDamage interface

ProjectileDamage component

Healing – IHeal interface

Controlling what damages/heals what

Updating the player and enemy to use health

Assigning the object with health – IHaveHealth interface

Process changes to health

Enemy wave spawner

Creating the enemy spawner Prefab

Integrating spawning with patrol behavior

Summary

9

Completing the Adventure Game

Technical requirements

Creating an event system in C# to tie things together loosely

The new event system

Systems GameObject

Creating a quest system for a collecting keys mission

The quest system

Script Execution Order

The quest

Collecting keys

Solving the key puzzle and winning the game

Sliding tile puzzle

Winning

Timeline

Summary

Part 4: 3D Game Design

10

Creating a 3D First Person Shooter (FPS)

Technical requirements

Designing for 3D while continuing the GDD

Greyboxing a 3D environment with ProBuilder and Prefabs

Habitat interior level

Installing ProBuilder

Modular parts, Prefabs, and Variants

Greyboxing the level design

Creating an FPS player character with the Unity Starter Asset

Installing the Unity Starter Assets

Starter Assets Playground scene

Getting around

Adding the first-person controller to our level

Playtesting the level

Refactoring environment interactions to 3D API methods

Revisiting the TriggeredEvent component

Implementing a TriggeredEvent in our level design

Animating the door opening

Code reuse in practice – Adding premade components to the player

Constant damage script

Inspector Debug

Recharging aka healing

Summary

11

Continuing the FPS Game

Technical requirements

Decorating the 3D environment

Updating and replacing Prefabs

Applying new materials

Immersing the player using Polybrush and Decals

Painting objects with Polybrush

Painting/scattering objects

Surface story with Decals

Lighting design – Probes, Decals, light baking, and performance

Setting the URP Forward+ Rendering Path

Proxy lighting with Decals (yes, Decals)

Bake that lighting?

Light Probes

Baked lighting dynamic shadows

Blob shadows

Summary

12

Enhancing the FPS Game with Audio

Technical requirements

Adding audio using the Audio Mixer

Sound design 101 for games

Adding audio to the game

Building an immersive soundscape with music, SFX, and ambiance

Playing music

Playing SFX

Playing SFX 3D

Playing ambient sound

Enhancing the audio experience with footsteps and reverb zones

Reusing audio player code

Adding a method overload to AudioPlayerSFX

Implementing AudioPlayerFootsteps

Implementing sprinting

Adding reverb zones

Deeper SOLID refactoring

Summary

Part 5: Enhancing and Finishing Games

13

Implementing AI with Sensors, Behavior Trees, and ML-Agents

Technical requirements

Refactoring the 2D enemy systems to 3D with NavMesh

Importing scripts from the 2D project

Refactoring the PatrolWaypoints class for NavMesh

Configuring the enemy NavMesh Agent (Prefab)

Adding waypoints to the level and testing

Dynamic enemies with sensors and behavior trees

Creating sensory behaviors

Wrangling behaviors with a behavior tree

Introducing ML with ML-Agents

Navigating training efficiency with NavMesh

Examining an ML-Agents setup

Summary

14

Entering Mixed Reality with the XR Interaction Toolkit

Technical requirements

Introduction to MR and development frameworks

XR Interaction Toolkit (XRI)

AR Foundation

OpenXR: Meta package

Designing a boss room

Setting up the physical space

Creating the Unity project

Laying out the boss room scene

Working with AR planes (AR Foundation)

Spawning using planes with AR Plane Manager

Instantiating on a table plane

Instantiating using the floor plane

Instantiating with wall planes

Toggling MR visuals with XR Input

Placing interactable objects in the world

Making objects XR interactables

Placing the modules in the room

Making the module slots interactable

Configuring the laser gun

Implementing the boss room mechanics

Solving the crystal modules puzzle

Spawning enemies

Completing the game loop

Summary

15

Finishing Games with Commercial Viability

Technical requirements

Introducing GaaS – UGS

Introducing Unity DevOps

Introducing Unity LiveOps

Safeguarding your investment! Source code management with Unity Version Control

Catering VCS for programmers

Catering VCS for artists

Catering VCS for Git

Setting up Unity Version Control

Engaging players with an in-game economy

Economies for mobile games

Economies for premium games

Contrasting economic strategies

Getting your game out there! Platform distribution

Distributing on mobile platforms

Distributing on PC platforms

Implementing UGS and publishing

Adding LiveOps services

Updating game content dynamically

Publishing with Unity Build Automation

Summary

Final words!

Index

Other Books You May Enjoy

Part 1: Introduction to Unity

The tasks outlined in this part will provide you with the necessary knowledge to navigate and utilize the Unity Editor effectively while creating new projects for your 2D games. Setting up the first 2D project of the book – a simple 2D top-down object collection game – will walk you through the key steps of project creation in the Unity Hub, introduce the Unity Editor windows and toolbars, create 2D objects in the Hierarchy and Scene windows, and set object properties such as Sorting Layers in the Inspector window.

This part includes the following chapter:

Chapter 1, Foundational Knowledge of Unity 2022

1

Foundational Knowledge of Unity 2022

Getting started in Unity 2022 is easy with Unity Hub. Unity Hub serves a few very useful purposes, and we’ll be going through installing it and learning about its features. In this chapter, we’ll not only install Unity Hub and the Unity Editor, but we’ll also break down the different templates that are available to kickstart your game and AR/VR projects.

In addition to templates that provide a starting foundation for your new project, Unity also provides added functionality through the Package Manager. The Package Manager allows Unity to give a small project size footprint and not bloat the Editor with a default installation of unneeded or unwanted tooling (referring to relatively simple add-on programs that combine to accomplish a task). Being familiar with and understanding what packages are available will surely help save time and increase the quality of your project.

Finding your way around the Unity Editor is only half an introduction. The second half of this chapter teaches you how to create content and make things interactable. We’ll do this by first creating a simple 2D character right in the Editor using built-in tooling. This all starts with the GameObject – Unity’s building block.

The book takes a project-based approach to learning, so we’ll walk through designing a game, creating a game, and solving problems along the way.

In this chapter, we’re going to cover the following main topics.

Unity Hub – choosing the 2D Universal Render Pipeline (URP) templateGetting to know the Unity Editor and installing packagesIntroducing the GameObject! All about the Transformand components2D Sprites with Sprite Creator – understanding the Sprite Renderer and draw orderingGame Design Document (GDD) – introducing the 2D collection game

By the end of this chapter, you’ll be able to create a new Unity project, be comfortable finding your way around the Unity Editor, understand the initial criteria for a game design document, and be prepared to create the 2D Sprite-based character that is the first element of our game.

Technical requirements

To follow along in this chapter, you’ll need a computer with Windows 7+ 64-bit, Mac OS X 10.12+, or Linux (Ubuntu 16.04, 18.04, and CentOS 7) running. You’ll need sufficient free hard drive space for not only the Unity Editor installation but also the project files. We recommend 25 GB for the Unity install folder, with 3 GB of free space for the installation temp files (the temp files are usually located on your OS installation drive), and 10 GB should be sufficient for the project files.

Unity Hub – Choosing the 2D URP template

The Unity Hub makes it simple to manage the installed Unity Editor versions and add or remove modules for installed Editors, and it helps manage your different projects. If you’re entirely new to Unity, then that previous sentence might be a bit confusing. Why would we have to manage different installed Editors? Simply put, software changes. As the Unity Editor evolves, it introduces new features and changes to its scripting API.

Tip

As a general rule of thumb, you should not upgrade the Unity Editor version for your project once you’ve started production. Doing so can have undesirable effects, such as broken renderings or code that no longer compiles. We’ll discuss this more in the following sections when installing the Unity Editor and selecting our project template.

Installing Unity Hub

Let’s get started on our journey by first getting Unity Hub installed. We’ll be using the Unity Personal license throughout this book, which is the free version of Unity. Free here doesn’t mean we will be limited in features or capabilities in building our games. It just means you are only allowed to use this version for free if you fall under the criteria for requiring a paid license (if you earned less than $100K of revenue or funds raised in the last 12 months).

Important note

If you are an eligible student, you may want to check out the Unity Student plan at https://unity.com/products/unity-student. It provides access to Unity Pro, a selection of quality assets, and Unity Gaming Services, such as Cloud Build, that professionals and studios building games use on Unity.

Okay, let’s do this. Perform the following steps to install the Unity Hub:

Go to https://unity.com/download and select the download link for your OS. This will download UnityHubSetup.exe to your Downloads folder.Click on the executable from your web browser, navigate to your Downloads folder, and double-click the executable to launch the installation.Keep the defaults or change the installation path if you want to install to a different hard drive location (only use local drives and not network drives, as this could cause problems).After clicking Install and letting the installation process complete, click Finish to run Unity Hub.

When opening Unity Hub for the first time, you will be prompted to Sign in or Create account if you have not created one already. Your Unity account, known as Unity ID, will be used for licensing. Unity requires an active license to install the Unity Editor. The Personal Edition license is free, and Unity Hub will generate one for you.

With Unity Hub now installed, let’s continue installing the Unity Editor.

Installing the Unity Editor – What version?

We have a new installation of Unity Hub and are now ready to install a Unity Editor version. As previously mentioned, Unity Hub allows you to have multiple versions of the Unity Editor installed to manage the different projects you’ll create over time. Opening Unity Hub without any Editor version installed will default to prompting the latest Unity Editor version in the LTS stream to be installed. LTS simply means long-term support. This is usually the best version choice to lock in and base a new project on because it will be the most stable version available and is guaranteed to be supported for the next two years. To ensure stability with the LTS version, no new features are added to the tooling or scripting API. If you want to create with the latest engine features, you’ll have to choose one of the newer tech streams since no additional tools or technologies will be introduced in the LTS stream.

Okay, simply stated, what does this mean?

If you’re starting production today or about to ship, and you desire stability and support over the lifetime of your development and release cycle, choose the LTS stream. At the time of writing, this is 2020.3 LTS.If you’re starting production today but want to leverage newer tools and technology, and the latest official release version is close to becoming the new LTS stream, choose the latest official release version. At the time of writing, this is 2021.2 (becoming the latest LTS stream when 2021.3 is officially released).If you want to create on the cutting edge of the tools and technology available and don’t mind managing potential crashes and bugs, then choose the latest pre-release (beta) version.

Important note

This book is written specifically for Unity 2022. If you have an earlier version of Unity already installed, then the instructions or features may differ, so it may be difficult – or impossible – to follow along. We recommend installing the latest version of Unity 2022 to complete the projects we’ll create in the following chapters.

To gauge your production schedule against the Unity LTS releases, refer to the following timeline:

Figure 1.1 – Unity platform release timeline

Unity provides detailed LTS release information on the Unity QA resources page at https://unity3d.com/unity/qa/lts-releases.

Proceed to install the Unity 2022 Editor with the following steps:

If you’ve just finished installing Unity Hub, you’ll be prompted to install the latest LTS version of the Unity Editor. We want to install a Unity 2022 release specifically, so proceed by clicking Skip installation in the lower-right corner of the dialog, unless, at the time you’re reading this, the 2022 LTS version has been released, in which case you can just install it and skip the remaining steps!In the main Unity Hub window, select Installs in the left-side pane.Click the Install Editor button in the window’s top-right corner.The Official releases tab should be selected by default (the latest beta versions can be found under the Pre-releases tab).In the OTHER VERSIONS section below the LONG TERM SUPPORT (LTS) section, find the latest 2022 release version listed and click Install.The next screen you’ll be presented with is selecting the dev tools, platforms, and documentation modules. Since we’re assuming you’re installing Unity for the first time, and we don’t currently have any specific requirements for our first project, we’ll just keep the defaults. Click on Continue.

Unity Hub will now download and install the selected version. Depending on your internet connection and hard drive speed, this will take a bit of time – an average base installation requires roughly 3 GB of downloads (temporary files) and approximately 7 GB of free hard drive space for installation.

In this section, we learned about the different Unity Editor versions available and how to install them. In the next section, we’ll learn about render pipelines to determine how to proceed with a new project.

What is a render pipeline?

In the next section, when we create our project, we’ll select a template to base our project on. This requires a bit of explanation to understand the templates’ options fully. We’ll create a 2D game (a two-dimensional game represented by planar images), so selecting a 2D template makes sense, but these are the available template names for 2D: 2D, 2D (URP), and 2D Mobile. We won’t be creating a mobile game, so we can rule out 2D Mobile, but what does (URP) mean?

If you’re unfamiliar with how video games work under the hood, rendering refers to how the 2D graphics or 3D models are drawn to the screen to generate an image. Over time, as Unity evolved its rendering technology to better suit the types of games creators were making, they understood the need to make changes and improve the rendering technology. A performant and customizable render pipeline architecture was introduced to serve creators best called a Scriptable Render Pipeline (SRP). The template named 2D will use Unity’s built-in renderer, whereas 2D (URP) will use the Universal Render Pipeline (Universal RP, or URP). The Universal RP is a default SRP Unity provides as a starting basis for making performant games on the broadest device platforms – this will eventually replace the built-in legacy renderer as the default.

Important note

We’ll discuss the URP feature set relevant to adding renderer features to the projects throughout the book but not compare it directly with the built-in renderer features. A feature comparison table between URP and the built-in renderer can be found at https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal%407.1/manual/universalrp-builtin-feature-comparison.html

This section taught you what a render pipeline is and how to select the correct 2D project template. Now you’ll use what you learned to create our first project!

Creating a project

We’ll be creating our project from scratch using one of the templates Unity Hub provides to make sure everything is set up correctly for our game’s rendering requirements. Since we’ll start by creating a 2D game, we’ll select the 2D (URP) Core template. Core means that the template won’t provide any example assets, samples, or learning content in this context. It will give an empty 2D project with a pre-configured URP 2D renderer setup – perfect, just what we need!

Proceed with the following steps to create a new 2D URP project in Unity Hub:

With Projects selected in the left-side pane, click the New project button in the window’s top-right corner.Verify that the Editor version at the top of the window is set to the installed 2022 version.Find the 2D (URP) template in the list and click to select it.Next, in the right-side pane, give your project a name by entering it in the Project name field.And finally, verify the installation path in the Location field, then click on Create project.

Now you can create your project with the preceding steps while referring to the following screenshot (making sure to have the correct Editor version selected at the top in case you have multiple versions installed already):

Figure 1.2 – Unity Hub project templates

In this section, you learned how to install the Unity Hub and installed a specific version of the Unity Editor. Then, you learned what a render pipeline is and how that relates to creating a new project. We’ll continue discussing the Unity Editor now by introducing its main features.

Getting to know the Unity Editor and installing packages

Having just created a new 2D URP project and opened up the Editor, let’s take a tour of the Unity 2022 interface! We’ll cover only the most common features in this section and dig deeper into the features of the specific windows and toolbars as we work through our projects in the later chapters, providing the information in the context of the required task.

When we open the Unity Editor for the first time, it will use the default Windows layout, as shown in the following screenshot:

Figure 1.3 – The Unity 2022 Editor default layout

The common Editor windows that you’ll be using most of the time are the following:

Scene – this is the window where we build our content visually. Objects added to the Scene Hierarchy with renderer components will be visible in the scene and game views.Game – the simulation you see in the game view represents what players will see rendered in your final playable distribution builds. You will also playtest your game in this window when entering Play Mode.Project – the Project window is comparable to your OS’s file manager. It’s where you’ll import and organize the files that make up the Assets for the project you’re creating (such as 3D models, 2D images, sounds & music, plugins, and so on).Hierarchy – this is the scene’s GameObject Hierarchy (more on GameObjects in the next section). Understanding how to organize your scene’s objects in the Hierarchy window (as in parent-child relationships) will be essential to work on your projects effectively, so this will be a topic of discussion in the coming chapters.Inspector – in the natural order of things in Unity, the Inspector window comes next as it’s tied directly to the GameObjects’ in the Hierarchy window. When an object is selected in the Scene Hierarchy, the Inspector shows all its details (Transformand components).Console – information, warnings, errors, and any relevant trace information are displayed in a list view that can be sorted and filtered. Debugging any problems occurring in your project will be performed from the Consoleinformation displayed.

Note that in the default layout, clicking on a tab, such as Game or Console in Figure 1.3, will bring it to the “front” for interaction. Tabs can also be dragged and docked to other windows to provide a fully customized layout.

In addition to these windows, Unity also has some toolbars, such as the following:

Figure 1.4 – The Unity 2022 Editor toolbars

Main Toolbar (A) – the buttons on the upper left provide access to your Unity Account (Unity ID), Unity Cloud Services, and the current version control system (VCS) (we’ll tackle version control in a later chapter). The centered buttons are the play (for entering Play Mode), pause, and step controls. On the right side, the buttons are Undo History, Global Search, the Layers Visibility dropdown, and finally, the Editor Layout dropdown (as noted earlier, we’re looking at the default window layout; you can change the layout using one of the presets or save your own).Scene Toolbar (B) – the tools, starting on the left side, are:Tool Handle Position (Center, Pivot) – when moving objects in the scene, the action will be based on this position, either the Center of the object or the object’s Pivot.

Tip

If the Anchor position of your GameObject in the scene View doesn’t look correct, don’t forget to check this setting!

Tool Handle Rotation (Global, Local) – when rotating objects in the scene, they rotate relative to their Transform in Global or Local space.

Tip

You may need to change between Global or Local space settings to rotate an object correctly. If your rotations don’t look correct, don’t forget to check this setting!

The remainder of the tools include grid visibility and snapping settings, Draw Mode, 2D or 3D scene View (we are currently in 2D), toggles for scene lighting, audio, effects, hidden objects, scene View camera settings, and Gizmos. There’s a lot to unpack here, but don’t worry, we’ll touch on these as we work through the projects we’ll be creating in the coming chapters.Manipulation Tools Toolbar (C) – a floating toolbar, also known as Overlays, within the Scene window. This toolbar provides the essential tools for working with GameObjects within the scene View. The tools include View, Move, Rotate, Scale, Rect, and Transform.

One more “toolbar” along the bottom of the Editor window is called the Status bar (not pictured). The Status bar mostly provides the current status of specific processes, such as the last Console warning or error message (left-side), the progress of lighting generation (right-side), and the code compilation spinner (right-corner).

Additional reading | Unity documentation

You can find more information on Unity’s interface at https://docs.unity3d.com/2022.3/Documentation/Manual/UsingTheEditor.html

In this section, you learned about the familiar Editor windows and toolbars and how they can manipulate objects in the scene View. Let’s see how we can extend the features and tooling in the Editor now with Packages.

The Unity Package Manager

Without knowing, you were already introduced to packages earlier when we discussed the Universal RP. Since we started with a URP template, we didn’t have to do anything special, but Unity provides Scriptable Render Pipeline support through packages! Packages provide a way for Unity to offer multiple versions of an engine feature or service without requiring a new installation of the Editor. You can even try out the latest pre-release version of a package to stay on the cutting edge of the technology and quickly revert to a stable or alternate version should you encounter any problems. The Package Manager is accessible from the top menu: Window | Package Manager.

Figure 1.5 – The Unity Package Manager

Feature sets in the Package Manager are bundles of common tooling that provide a simpler and more streamlined install experience. The 2D feature set (selected in Figure 1.4) is for creators working with 2D projects. In our case, again, having started from the 2D URP template, the 2D feature set has already been imported to our project (indicated by the green checkmark). We’re good to go!

Should you need to make any changes to the packages in your project, from the dropdown in the Package Manager top menu, you can see what packages are available from what is already in your project via In Project, or either the Unity Registry or My Assets (which are assets you’ve purchased in the Unity Asset Store) selections. Managing a package is as simple as selecting it in the list and choosing an available function from the buttons displayed in the bottom-right window. For example, Download, Install, Remove, or Update.

Tip

Packages are project-specific, so you will need to ensure you have the desired packages installed for each new project you create!

New to Unity 2022

In the Package Manager window, you can now multi-select packages in the list for adding, updating, or removing in a single operation.

In this section, you learned about the Editor windows and toolbars and how to add/remove features and tooling with packages that extend the Editor’s capabilities. Next, we’ll start learning about the GameObject.

Introducing the GameObject – All about Transform and components

Simply put, anything you want to add to your scene will be added as a GameObject. The GameObject is the base building block for everything that exists in a scene. It also acts as a container for adding functionality with components. When a GameObject is added to the Hierarchy, is it active by default but can be deactivated – “turning off” all components added to it – with the checkbox to the left of the name field (to the left of Main Camera in Figure 1.6). A component can be for either visual or functional purposes, or in some cases, both! Functional components implement Unity’s scripting API, and Unity provides components for supporting the engine’s many features. You’ll create custom component scripts using the C# language, which will be covered in Chapter 2.

In this section, you will learn how GameObjects are added to a scene, then you’ll be introduced to the Transform component, and you’ll learn how to work with components.

Adding GameObjects to the scene

New empty GameObjects and objects of a specific type are easily added to the Hierarchy with the Create menu. The Create menu is easily accessible from Unity’s top menu under GameObject, from the Hierarchy window directly with the + (plus sign) icon dropdown menu at the top, or by right-clicking anywhere in the Hierarchy window. GameObjects in the form of Prefabs and other supported types can be added to the scene View directly by dragging and dropping from the Project window – this is often the quickest way to accomplish some tasks, and we’ll be exploiting this feature while building the book’s projects.

The Transform component

GameObjects added to the scene have a default Transform component that dictates its Position, Rotation, and Scale in 3D space – a Cartesian coordinate system using three mutually perpendicular coordinate axes with Y-Up, namely X-axis, Y-axis, and Z-axis. Positioning graphics in the scene can be performed by either manipulating the Transform manually (by typing in values), with the Manipulation Tools (clicking and dragging in the Scene window), or through code by using the Unity scripting API to access the GameObject’s Transform properties and methods.

In the following screenshot, we can see the Main Camera GameObject’s Transform in the Inspector and how the Position value (Vector3) is represented in 3D space:

Figure 1.6 – Inspector Transform and related 3D coordinate system

In the preceding figure, we can see that the Main Camera (a GameObject) in the scene was selected in the Hierarchy because its name is stated at the top of the Inspector window. The following section under that is the GameObject’s Transform values indicating that Main Camera is sitting -10 units on the Z-axis from the origin (0, 0, 0 where all axes intersect). The Rotation values on all axes are at 0, meaning no rotation is applied to this GameObject. Similarly, the Scale value on all axes is at 1, meaning no scaling is applied to the default scale of this GameObject. We’ll modify these values in context while creating our player character graphics in the 2D sprites with Sprite Creator – Understanding the Sprite Renderer and draw ordering section.

Before creating our player, let’s discuss components in more detail since we’ll be directly working with them.

Components

Below the Transform section, we can see several components already added that provide functionality for the GameObject’s purpose as our scene’s main camera (cameras in our Scene Hierarchy determine what the player sees rendered in the game view). To add more functionality to this camera, click the Add Component button at the bottom of the Inspector window. You’ll be presented with a filtered and searchable list of available components to add. The components will include not only the ones provided by Unity, such as the Camera component in Figure 1.6, but also any scripts you’ve already created and added to the project. In the next chapter, we’ll tackle creating our scripts and adding them as components.

Components can be added, removed, and copied/pasted, and their values can be copied/pasted and even saved as presets! This is all accomplished via the Component header section. Click and hold the header to manually reposition a component up/down in the Inspector window or right-click for moving and other functions. All of the aforementioned functions are accessible either through the right-click dialog popup or the icons on the right side of the component header; those are Reference, Presets, and a vertical ellipsis equivalent to right-clicking in the title.

Components add powerful features to your projects, but things come together even more when components combine and work together with other components. Unity is based on this component architecture. We will be diving into how to structure your projects best to leverage Unity components in a well-structured single-responsibility design pattern that is easy to work with and friendly for both designers and developers to use.

In this section, you learned about the importance of components and how to work with them in Inspector. We’ll be working with components throughout the book, starting with the Sprite Renderer in the next section.

2D sprites with Sprite Creator – Understanding the Sprite Renderer and draw ordering

Let’s dig right in and put into practice what we just learned about GameObjects by creating a simple sprite-based character we’ll be using as the player in a collection game. This will be our first project in the book! We’ll make the player character from scratch using Unity’s built-in Sprite Creator graphics.

In this section, we’ll create a new scene, add sprites, and learn how to manipulate and layer sprites together to make our player character.

Creating a new scene

First, let’s create a new scene by going to File | New Scene (or using the Ctrl/Cmd + N shortcut). This will open the New Scene dialog and prompt us to select a Scene Template. We’re going to be using the Lit 2D (URP) template since we’ll be working with 2D while also using the Universal RP, and we want to take advantage of all the advanced lighting features URP offers.

Important note

When the scene opens, it’s good practice to save it immediately! Save it now by going to File | Save (or by pressing Ctrl/Cmd + S), selecting a folder in your project (usually Assets/Scenes), and giving it a descriptive name. Now, anytime you make changes and want to save your progress, simply use the Ctrl/Cmd + S shortcut to save. You’ll want to do this regularly and make it a habit – crashes occur when you least expect it, and you don’t want to lose any significant progress that will have to be recreated.

With our new scene being created, let’s add some sprites!

Creating a sprite using Sprite Creator

Next, create a sprite in our scene using the Create menu by right-clicking within the Hierarchy window (or using the + dropdown at the top of the window) and then going to 2D Objects | Sprites | Circle. You should now have a circle visible in your scene View placed at the origin position of (0, 0, 0). Yay!

Let’s parent this to a new empty GameObject to create our player object with a good structure – separating the graphics from the functionality we’ll add as components to the root GameObject. We’ll do this by performing the following steps:

Create a new empty GameObject by, again, right-clicking within the Hierarchy window (or using the + dropdown at the top of the window) and then selecting Create Empty. Newly created GameObjects will be positioned at the origin position of (0, 0, 0).The default name of a new GameObject, as you guessed it, is GameObject. It is highlighted for editing by default, so you can easily rename it without additional steps. We’ll use the default name for now, so hit the Enter key.Create another new GameObject, but this time name it Graphics.Now, we’ll set up the player character’s GameObject structure by drag and drop. First, click and drag the Circle object to Graphics, then click and drag the Graphics object to GameObject.

Important note

We could have saved a few steps by first selecting the Circle GameObject in the Scene Hierarchy, right-clicking on it to open the Create menu, then selecting Create Empty Parent. The previous process was essential to demonstrate how GameObjects in the Hierarchy window can be parented and moved to other positions in the Hierarchy. To give this a try now, undo the parenting by going to Edit | Undo (or Ctrl/Cmd + Z) and then redo the parenting of the GameObjects.

Finally, rename the root object from GameObject to Player. First, select it in the Hierarchy window and press the F2 (Windows) or Enter (Mac) key. Alternatively, with the chosen item in the Hierarchy, use the name field at the top of the Inspector window to rename it. You should end up with the following sprite and GameObject setup in your scene:

Figure 1.7 – 2D Sprite player character GameObject Hierarchy

You learned how to add a sprite shape to your scene and understand the parenting of GameObjects to create a good structure. Before tapping fully into your arcane artistic talents to create our player character, knowing how to get around in the scene View first will surely be beneficial.

Navigating the scene View

Moving around in the scene View will help your drawing efforts by zooming in/out on details and focusing on the part you’re working on. While in 2D Mode, you’ll exclusively be using both panning and zooming:

Pan the scene View around by pressing the right-mouse button, using the View Tool (“hand” icon in the Toolbar Overlay) by clicking and dragging, or you can also use the keyboard by pressing the arrow keys.Zoom in/out of the scene View by scrolling the mouse wheel.Additionally, you can bring focus on an object in the scene View by double-clicking it in the Hierarchy window.

Additional reading | Unity documentation

You can read more about scene View navigation at https://docs.unity3d.com/2022.3/Documentation/Manual/SceneViewNavigation.html

We’re all set to start building our character in the next section.

Creating our player character

We will create a ladybug for the player character in our collection game project. We’ll use Sprite Creator sprites to design our character right inside the Unity Editor! In a later chapter, we’ll be importing original art assets to use as the different sprites in the game. For now, we’ll be limited to using some basic shapes to build out our character design, but with some creativity, the results can look quite lovely. The Transform values for Position, Rotation, and Scale and their corresponding Manipulation Tools (Toolbar Overlay) will be used extensively to draw our character.

Important note

Placeholder graphics created by a programmer during early development – and in some cases, before an artist has finalized artwork – are commonly referred to as “programmer art.” This term is sometimes used negatively to indicate mediocre artwork, but don’t let that stop you from being creative! Games such as Geometry Dash, 140, and VVVVVV all use simple graphics to great effect.

Let’s start by selecting the Circle object (that we previously created) in the Hierarchy window (or double-clicking to bring it into focus in the scene View) – note that we’ll want to keep all our new sprites as children of the Graphics object in the Hierarchy (as seen in Figure 1.8). This will be the ladybug’s body, so let’s give it a nice red color.

The Sprite Renderer component has a field for color just below the Sprite field that indicates we’re using the Circle sprite shape. Clicking the color will pop up the Color Picker dialog (see Figure 1.8). When you have a nice shade of red selected – as indicated in the top-right corner of the dialog – simply click the close button in the dialog’s title bar (the x).

Figure 1.8 – The Ladybug Sprite Renderer component and the Color Picker dialog

With our body sprite having a nice shade of red, we can now shape it by manipulating its Transform in the next section.

Using Manipulation Tools

In Figure 1.8, you can see that we’ve already gone ahead and finished our ladybug character design. Let’s walk through the process of creating it now. You should have a red circle in your scene View, but it needs to be… less circular. Let’s turn it into an ellipse by scaling it on its Y-axis. This can be accomplished by either typing in a value in the Transform | Scale | Y field or adjusting manually using the Rect Tool (selected in the Toolbar Overlay in Figure 1.8, and Scale Tool may also be used).

Important note