Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Unity 2022 by Example
Unity 2022 by Example

Unity 2022 by Example : A project-based guide to building 2D and 3D games, enhanced for AR, VR, and MR experiences

By Scott H. Cameron
$39.99 $27.98
Book Jun 2024 596 pages 1st Edition
eBook
$39.99 $27.98
Print
$49.99
Subscription
Free Trial
Renews at $15.99p/m
eBook
$39.99 $27.98
Print
$49.99
Subscription
Free Trial
Renews at $15.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Unity 2022 by Example

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) template
  • Getting to know the Unity Editor and installing packages
  • Introducing the GameObject! All about the Transform and components
  • 2D Sprites with Sprite Creator – understanding the Sprite Renderer and draw ordering
  • Game 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:

  1. Go to https://unity.com/download and select the download link for your OS. This will download UnityHubSetup.exe to your Downloads folder.
  2. Click on the executable from your web browser, navigate to your Downloads folder, and double-click the executable to launch the installation.
  3. 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).
  4. 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

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:

  1. 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!
  2. In the main Unity Hub window, select Installs in the left-side pane.
  3. Click the Install Editor button in the window’s top-right corner.
  4. The Official releases tab should be selected by default (the latest beta versions can be found under the Pre-releases tab).
  5. In the OTHER VERSIONS section below the LONG TERM SUPPORT (LTS) section, find the latest 2022 release version listed and click Install.
  6. 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:

  1. With Projects selected in the left-side pane, click the New project button in the window’s top-right corner.
  2. Verify that the Editor version at the top of the window is set to the installed 2022 version.
  3. Find the 2D (URP) template in the list and click to select it.
  4. Next, in the right-side pane, give your project a name by entering it in the Project name field.
  5. 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

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

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 (Transform and 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 Console information 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

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

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

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:

  1. 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).
  2. 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.
  3. Create another new GameObject, but this time name it Graphics.
  4. 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.

  1. 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

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

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

The 2D scene View is represented by the X and Y axes for horizontal and vertical values, respectively. The Z-axis would represent depth, but in 2D Mode, we won’t be manipulating the Z-axis value and will be using Sprite Sorting and Ordering in Layers.

While manipulating manually with the Rect Tool, click and drag on the edge (1 axis) or corner (2 axes) of the box surrounding the Circle object to resize it.

Two modifier keys that can help create shapes more easily are the Shift and Alt keys – but keep the keys pressed while dragging, do not press them before doing so.

  • To maintain the current aspect ratio while scaling, hold down the Shift key while dragging.
  • To scale an object equally on both sides from the center pivot, hold down the Alt key while dragging.

Tip

You can hold both the Shift and Alt keys down while manipulating an object.

When you have a body shape that looks good, let’s move on by creating an outline for it. An outline will help provide a good separation of our player character from the background environment. With the Circle object still selected (you can simply click on shapes in the scene View to select them), press Ctrl/Cmd + D to duplicate it. This will create a copy of the Circle sprite and append a number incrementally to the name for every duplicate made. Set the new shape’s color to black and scale it up uniformly to be slightly larger than the red circle. While performing this action, you’ll likely realize that we now have a problem – the black shape hides the red body. Let’s fix it.

Sprite Layers and Ordering

In Inspector, Additional Settings is a section within the Sprite Renderer component. If the Sorting Layer and Order in Layer fields are not visible directly underneath it, click on Additional Settings to expand it (refer to the bottom of the Inspector window in Figure 1.7). We can change the drawing order of sprites in two ways: 1) by specifying Sorting Layer or 2) by a value specified in the Order in Layer field.

Sorting Layers is a topic we’ll be diving into in the coming chapters since we only need a single Layer for our current purpose – think of Layers as pages in a book where the order in which they are read front to back can be rearranged. Now, working with the Order in Layer field, we enter positive and negative integer values to set the sprites drawing order front to back on its Sorting Layer (currently Default). The default value is 0, putting every shape at the same depth. Since we want the black shape to be in the back of the red shape, set its Order in Layer value to -1. You can now readjust its size to give a nice outline thickness to the red shape.

Tip

You can select multiple shapes and change the Order in Layer value for all at once by holding the Ctrl or Shift key when selecting.

Creating the rest of the ladybug character is just a matter of duplicating a sprite shape already in the scene or creating a new one. The Sprite Creator shapes available are square, circle, capsule, diamond, and hexagon.

Move the shapes into position by simply clicking and dragging on the sprite in the scene View and placing it in position. Hovering the mouse pointer near the corner point (blue dot) will show the rotation cursor. While this cursor is showing, clicking and dragging will rotate it.

Additional reading | Unity documentation

You can read more about positioning GameObjects at https://docs.unity3d.com/2022.3/Documentation/Manual/PositioningGameObjects.html

Go ahead and create your own ladybug player character now. Use all of the Transform fields, Rect Tool with the modifier keys, and the Order in Layer field to draw. You will perform these actions repeatedly throughout creating the projects in the book for not only sprites but also UI elements. Have fun with it!

In this section, you learned how to create a new Scene, add and duplicate sprites, and manipulate those sprites to make our player character with the Order in Layer value. Next, before wrapping up this chapter, we’ll discuss game design.

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

Throughout the book, the game we’ll be creating will be defined and structured using what is known as Game Design Document (GDD). This document will serve as our point of reference as we decide how to develop the game’s core aspects. Our game is going to be pretty simple but packed with features. Most of the information written in the GDD is self-explanatory, but a few concepts might be new, so let’s start by reviewing them:

  • What is the name of the game?
    • This one is self-explanatory, so just don’t stress over this now! Anything as a working title will work just fine – have fun with it.
  • What is the game’s core loop?
    • The core loop is what makes your game an enjoyable and satisfying experience for players. It is the series of actions the player repeatedly performs to accomplish the objective.

Let’s see an example GDD filled out for the 2D collection game we’ll make throughout the book:

Name of Game

Outer World

What is the theme, setting, or genre?

2D Sci-fi Platformer

Summary

What’s the big picture?

An adventure game that takes the player on a journey from peaceful farming to battling robotic systems infected by an evil alien plant entity. The game takes place on an alien planet where the player’s race has established a habitat on the planet’s surface. The habitat is fully automated and maintained by robots managed by a central control system. An evil alien plant entity has infiltrated the control systems and taken over the robots individually and the central system. The goal of the alien entity is not known, but it must be stopped if the player’s race is to survive on this planet.

What is the game’s unique feature?

Multiple game modes provide a novel and exciting approach to gameplay: simulation, adventure, and shooting.

What games inspired you and why?

Metroid, Mega Man, and Stardew Valley.

Describe the gameplay, the core loop, and the progression.

Collect energy shards to clean seedlings in a space station habitat as the timer ticks down!

Table 1.1 – GDD for the game

As needed, we’ll be adding to the GDD over time, but this will serve us well as a starting point. Yay!

This section introduced you to a simple GDD template and you learned the basic but essential questions to answer when making a remarkable game.

Summary

This chapter was a quick introduction to installing Unity Hub, installing the Unity Editor, and why we chose the 2D Universal RP template for creating our new 2D project. In this chapter, you learned the importance of Package Manager for adding tooling and features to the Unity Editor specific to our project’s needs. You then learned how to make your way around the different windows and toolbars, and you used them to create and manipulate GameObjects in our new 2D scene. We also got a headstart on building the collection game by drawing our player character within the Unity Editor – learning the importance of Layer sorting order in the process.

Finally, we started defining what the game we’re creating will be by deciding on a name for the game, writing our summary, and specifying some gameplay in the GDD – this will provide the necessary direction for the production of the game.

In the next chapter, we’ll dive into creating the “Outer World” collection game environment, learning how to implement game mechanics through scripts, and adding a basic UI.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Create game apps, including a 2D adventure game, a 3D first-person shooter, and more
  • Get up to speed with Unity Gaming Services available for creating commercially viable games
  • Follow steps for publishing, marketing, and maintaining your games effectively
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

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.

What you will learn

Build game environments and design levels, and implement game mechanics using Unity's features Explore 3D game creation, focusing on gameplay mechanics and player animation Develop customizable game systems using object-oriented architecture Build an MR experience using the XR Interaction Toolkit while learning how to merge virtual and real-world elements Get up to speed with advanced AI interactions using sensors and Unity's machine learning toolkit, ML-Agents Implement dynamic content in games using Unity LiveOps services like Remote Config

Product Details

Country selected

Publication date : Jun 7, 2024
Length 596 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803234595
Vendor :
Unity Technologies
Category :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details


Publication date : Jun 7, 2024
Length 596 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803234595
Vendor :
Unity Technologies
Category :
Tools :

Table of Contents

23 Chapters
Preface Chevron down icon Chevron up icon
1. Part 1: Introduction to Unity Chevron down icon Chevron up icon
2. Chapter 1: Foundational Knowledge of Unity 2022 Chevron down icon Chevron up icon
3. Part 2: 2D Game Design Chevron down icon Chevron up icon
4. Chapter 2: Creating a 2D Collection Game Chevron down icon Chevron up icon
5. Chapter 3: Completing the Collection Game Chevron down icon Chevron up icon
6. Part 3: 2D Game Design Continued Chevron down icon Chevron up icon
7. Chapter 4: Creating a 2D Adventure Game Chevron down icon Chevron up icon
8. Chapter 5: Continuing the Adventure Game Chevron down icon Chevron up icon
9. Chapter 6: Introduction to Object Pooling in Unity 2022 Chevron down icon Chevron up icon
10. Chapter 7: Polishing the Player’s Actions and Enemy Behavior Chevron down icon Chevron up icon
11. Chapter 8: Extending the Adventure Game Chevron down icon Chevron up icon
12. Chapter 9: Completing the Adventure Game Chevron down icon Chevron up icon
13. Part 4: 3D Game Design Chevron down icon Chevron up icon
14. Chapter 10: Creating a 3D First Person Shooter (FPS) Chevron down icon Chevron up icon
15. Chapter 11: Continuing the FPS Game Chevron down icon Chevron up icon
16. Chapter 12: Enhancing the FPS Game with Audio Chevron down icon Chevron up icon
17. Part 5: Enhancing and Finishing Games Chevron down icon Chevron up icon
18. Chapter 13: Implementing AI with Sensors, Behavior Trees, and ML-Agents Chevron down icon Chevron up icon
19. Chapter 14: Entering Mixed Reality with the XR Interaction Toolkit Chevron down icon Chevron up icon
20. Chapter 15: Finishing Games with Commercial Viability Chevron down icon Chevron up icon
21. Index Chevron down icon Chevron up icon
22. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Top Reviews
No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.