CRC Mastering Unity
CRC Mastering Unity
DOI: 10.1201/9781003214755
Typeset in Minion
by KnowledgeWorks Global Ltd.
Contents
v
vi ◾ Contents
Scene Templates 84
Creating Scene Templates 85
Modifying Scene Templates 87
Customizing the Creation of New Scenes 90
The Sequence of Scene Template
Instantiation 91
Settings for the Scene Template 93
New Scene Settings 93
Types Settings by Default 94
WHAT ARE GAMEOBJECTS? 94
Specifications 95
Transforms 96
The Component of Transform 96
Properties 97
Transform Editing 97
Parenting 98
Non-Uniform Scaling Limitations 99
Scale’s Importance 100
Working with Transforms: Some Pointers 101
Components Are Introduced 101
Configurations of Common Components 102
Component Transformation 102
Components of the Main Camera
GameObject 102
Making Use of Components 102
Adding Components 103
x ◾ Contents
Metal 195
Restrictions and Requirements 196
Metal Enabling 196
Metal API Validation 197
Core OpenGL 197
Activating OpenGL Core 197
OpenGL Specifications 198
Limitations of the macOS OpenGL
Driver 198
Features of OpenGL Core 198
Command-Line Parameters for the OpenGL
Core Profile 199
Native OpenGL ES Command-Line
Parameters on Desktop 200
GRAPHICS PERFORMANCE OPTIMIZING 200
Find High-Impact Graphics 200
CPU Enhancement 202
OnDemandRendering CPU
Optimization 203
GPU: Model Geometry Optimization 204
Lighting Efficiency 205
Forward Drawing of Lights 206
Texture Compression and Mipmaps
on the GPU 207
Mipmaps for Textures 208
LOD and Cull Distances Per Layer 208
Shadows in Real Time 208
Contents ◾ xvii
APPRAISAL, 237
INDEX, 247
About the Editor
xix
Chapter 1
Introduction
to Unity
DOI: 10.1201/9781003214755-1 1
2 ◾ Mastering Unity
skills. This is wonderful for indie devs that are just getting
started with Unity development.
The Pro tier is intended for game studios and profes-
sional teams that require in-house assistance and those
that earn more than $200,000 from Unity projects.
Overall Views
We’ve been using Unity 3D for many years so that we can
share firsthand comments and pitfalls.
First and foremost, we believe Unity is an excellent
engine. It’s not the finest, but it’s a fantastic, well-rounded
tool that’s ideal for novices.
Second, there is no such thing as the most refined gam-
ing engine. There are only tools available for the job. Some
are superior to others, and it all depends on the require-
ments of the unique project. While we’ll need coding abili-
ties to utilize Unity, tools can help us learn anything we
choose.
A short Google search yields code samples and mate-
rials for everything from first-person shooters to candy-
crush-style matching games and everything in between.
However, there are compelling reasons to master coding in
addition to 3D/computer graphics (CG) jobs. Unity is, at its
core, a well-rounded game engine that simplifies game pro-
duction. While there may be better engines to use based on
our project’s requirements, understanding Unity can only
help us improve as a game developer.
Unity is the way to go if we’re a complete newbie because
the community will assist learns, and the tools will last a
long time. If we’re more experienced, we could prefer
12 ◾ Mastering Unity
• System Requirements
• Operating system version: Windows 7 (SP1+),
Windows 10, and Windows 11, 64-bit versions
only.
• CPU: X64 architecture with SSE2 instruction set
support.
• Graphics API: DX10, DX11, and DX12-capable
GPUs.
• Additional requirements: Hardware vendor offi-
cially supported drivers.
• Mobile
• Operating system
• Version: 4.4 (API 19)+
• CPU: ARMv7 with Neon Support (32-bit) or
ARM64
• Graphics API: OpenGL ES 2.0+, OpenGL ES
3.0+, and Vulkan
• Additional requirements: 1GB+ RAM
Introduction to Unity ◾ 13
• Desktop
• Operating system
• Version: Windows 7 (SP1+), Windows 10, and
Windows 11.
• CPU: x86, x64 architecture with SSE2 instruction
set support.
• Graphics API: DX10, DX11, DX12 capable.
• Additional requirements: Drivers were officially
supported by the hardware vendor.
ARCHITECTURE OF UNITY
The Unity engine is written in native C/C++, but we
interface with it through a C# layer. As a result, we must
be familiar with some of the fundamental notions of C#
scripting. This part of the User Manual describes how
Unity implements .NET and C#, as well as any errors you
may see when coding.
Backend Scripting
Unity features two scripting backends: Mono and IL2CPP
(Intermediate Language To C++), each with its compila-
tion technique:
Collection of Garbage
For both the Mono and IL2CPP backend, Unity employs
the Boehm garbage collector. By default, Unity employs
the Incremental mode. Although Unity suggests using
Incremental mode, you may disable it to employ “stop the
world” trash collection.
To switch between Incremental mode and “stop the
world,” navigate Edit > Project Settings > Player, open the
Other Settings panel, and tick the Use incremental GC
checkbox. In Incremental mode, Unity’s garbage collector
runs for a limited duration and may not always gather all
objects in a single pass. This distributes the time it takes
to acquire things across many frames, reducing stuttering
and CPU spikes.
Use the Unity Profiler to examine the amount of allo-
cations and potential CPU spikes in your application. We
may also use the GarbageCollector API to deactivate trash
collection entirely in players. When the collector is turned
off, we should take care not to allocate too much memory.
Overhead Reflection in C#
All C# reflection (System.Reflection) objects are cached
internally by Mono and IL2CPP, and Unity does not trash
18 ◾ Mastering Unity
Serialization of Scripts
Serialization is the act of automatically converting data
structures or object states into a format that Unity can
store and rebuild later. This section includes information
on how to utilize serialization effectively in our Project.
Script Compilation
How and in what sequence Unity builds your programs.
This section also includes information on Assembly
Definitions and best practices for utilizing them.
Introduction to Unity ◾ 21
Setting Up Unity
DOI: 10.1201/9781003214755-2 29
30 ◾ Mastering Unity
• Accept the license and terms, and then press the Next
button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript :
MonoBehaviour
{
// This should be used for startup
void Start()
{
}
// The update function is called once each
frame
void Update()
{
}
}
void Update()
{
float hi = Input.
GetAxisRaw("Horizontal");
float vi = Input.GetAxisRaw("Vertical");
gameObject.transform.position = new
Vector2 (transform.position.a + (hi *
speed), transform.position.b + (vi *
speed));
float hi = Input.GetAxisRaw("Horizontal");
float vi = Input.GetAxisRaw("Vertical");
body.velocity = new Vector2(hi * speed, vi
* speed);
}
}
void Update ()
{
if (Input.GetKeyDown(keyToDestroy))
{
Destroy (gameObject);
}
}
}
COROUTINES IN UNITY
When creating games with Unity, the most valuable tools
are coroutines. Consider the following piece of code to
grasp better what coroutines are all about.
IEnumerator MyCoroutineMethod()
{
// code
yield return null;
}
Setting Up Unity ◾ 55
void Start ()
{
srr = GetComponent<SpriteRenderer>();
StartCoroutine(ChangeColor());
}
IEnumerator ChangeColor()
{
while (true)
{
if (srr.color == color1)
sr.color = color2;
else
srr.color = color1;
yield return new WaitForSeconds(3);
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
Debug.Log("Space-key pressed!");
}
After we’ve saved, compiled, and ran this code (by con-
necting it to a GameObject, of course), try hitting the
spacebar. Our message will be written out if we click on
the Console tab.
Similarly, the LogWarning and LogError methods can
be used to produce cautions and errors, respectively. These
will be handy for testing tiny pieces of code without having
to implement them.
Components of Audio
We will learn about the three essential audio components
in Unity.
Making a Noise
Let’s attempt to build a button that emits a sound when
pressed. To begin, we will create a Circle sprite and color
it red.
Let us now add an Audio Source to this sprite. We must
provide a sound for the item for it to play one. Let’s put this
sound effect to good use:
https://orangefreesounds.com/ding-sfx/.
Drag the sound effect into the Assets folder.
When Unity imports this asset as a sound file, it con-
verts it to an AudioClip automatically. As a result, we may
drag this sound clip directly from the Assets to the Audio
Clip slot in our sprite’s Audio Source.
Remember to deselect “Play on Awake” in the Audio
Source attributes after dragging the sound clip from the
Assets straight onto the Audio Clip slot in our sprite’s
Setting Up Unity ◾ 61
Let us now put up the technique for detecting the object that
has been clicked. MonoBehaviour provides us with the method
we require, OnMouseDown. When the mouse is within the
range of a collider of that gameObject, the function is invoked.
Let us connect a collider to our button now because we
haven’t done so yet.
We won’t require a Rigidbody for this one nor will we
need to access it via code. It only needs to be present for the
procedure to operate.
Let us put the approach to the test and see whether it works.
Add the following code to our script and link it to the button.
void OnMouseDown()
{
Debug.Log("Click");
}
62 ◾ Mastering Unity
Play the game after saving and attaching the script. When
we click the button, a message should appear in the Console.
We are now one step closer to hearing the sound. All
that remains is to invoke the Play method on the Audio
Source object.
void OnMouseDown()
{
mySource.Play();
}
using UnityEngine;
using UnityEngine.UI;
public class ButtonBehaviour: MonoBehaviour
{
int a;
public Text myText;
public void OnButtonPress()
{
a++;
myText.text = "Button clicked " + a + "
times.";
}
}
void Update()
{
myText.text = "Current Volume: " +
mySlider.value;
}
}
Working with
Scenes and
GameObjects
DOI: 10.1201/9781003214755-3 73
74 ◾ Mastering Unity
Using the New Scene dialog to create a new scene: Use the
New Scene dialog to generate new scenes from specified
scene templates in our Project. The New Scene dialog may
also be used to identify and manage scene templates. See
The New Scene dialog for more information.
The New Scene dialog appears by default when we cre-
ate a new scene through the menu (File > New Scene) or by
using a keyboard shortcut (Ctrl/Cmd + n).
To make a new Scene, follow these steps:
Multi-Scene Editing
This feature allows us to have numerous scenes open in the
editor simultaneously, making it easier to handle scenes at
runtime.
The option to access several scenes in the editor allows
us to construct massive streaming worlds and enhances
efficiency while working on scene editing together.
78 ◾ Mastering Unity
Play Mode
In-Play mode, when there are several scenes in the
Hierarchy, an additional scene called DontDestroyOnLoad
will appear.
Prior to Unity 5.3, any objects constructed in Playmode
and marked as “DontDestroyOnLoad” would stay in the
hierarchy. These items are not considered part of any
scene, but they are now presented as part of the unique
DontDestroyOnLoad scene for Unity to display and for
you to study.
The DontDestroyOnLoad scene is not accessible to us,
and it is not available during runtime.
Scene-Specific Settings
Each scenario has its own set of settings. They are as
follows:
Navmesh configuration Scene settings in the
RenderSettings and LightmapSettings sections of the
Occlusion Culling Window (both located in the Lighting
Window)
Each scene manages its settings, and only the param-
eters connected with that scene are saved to the scene
file.
If we have several scenes open, the rendering and
navmesh settings from the active scene are utilized. This
implies that if we wish to modify the settings of a scene,
we must either open only one scene and do so or make the
scene in question the active scene and do so.
When we change the current scene in the editor or dur-
ing runtime, all of the settings from the new scene are
applied and replace all prior settings.
Working with Scenes and GameObjects ◾ 83
Scripting
Scene Templates
Unity replicates scene templates to generate new scenes.
Consider a scene template to be a pre-configured scene
with all of the stuff we wish to begin with. The Basic
template, for example, generally includes a Camera and
a light.
Working with Scenes and GameObjects ◾ 85
SceneTemplate.CreateSceneTemplate(string
sceneTemplatePath)
SceneTemplate.CreateTemplateFromScene(
SceneAsset sourceSceneAsset, string
sceneTemplatePath);
Property Description
Template scene Specify which scene will be used as a
template. This might be from any
scenario in the Project.
Title The name of the template. The name you
provide here will be shown in the New
Scene dialog.
Description The description of the template. The
explanation we put here will be shown in
the New Scene dialog.
Pin in New Scene dialog This setting determines whether or not
this template gets pinned in the New
Scene dialog.
Pinned templates are always displayed at
the top of the Scene Templates list in the
Project list.
Property Description
Texture This property specifies a Texture asset to be
used as a thumbnail for this template. In the
Project, we may utilize any Texture asset.
If we don’t provide a Texture, the template
will utilize the asset icon from the default
scene template.
[Thumbnail Preview] If the template contains a thumbnail texture,
it will be shown.
Snapshot This template has options for capturing a
thumbnail picture.
View Specifies whether the Main Camera view or
the Game View should be captured.
Take Snapshot To save the selected View, click this button.
Example:
using UnityEditor.SceneTemplate;
using UnityEngine;
using UnityEngine.SceneManagement;
public class
DummySceneTemplatePipeline1 :
ISceneTemplatePipeline
{
Working with Scenes and GameObjects ◾ 91
Option: Description:
New Scene menu
New Scene dialog The New Scene dialog box is being shown.
Built-in Scene Without opening the New Scene dialog, this
command creates a new scene. The new scene is
a clone of the Basic template from the Project.
94 ◾ Mastering Unity
Specifications
A Transform component (which represents position and
orientation) is constantly associated with a GameObject
and cannot be removed. The additional components
that provide the object’s functionality can be added
using the editor’s Component menu or a script. There
are also numerous helpful pre-constructed objects
(basic shapes, Cameras, and so on) accessible under the
GameObject > 3D Object menu; see Primitive Objects
for more information.
96 ◾ Mastering Unity
• Transforms.
• Introduction to components.
• Using Components.
• Deactivating GameObjects.
• Tags.
• Static GameObjects.
Transforms
The Transform is used to hold the position, rotation, scale,
and parenting status of a GameObject and is thus highly
significant. A Transform component is always associated
with a GameObject; it is impossible to delete or construct a
GameObject without one.
Properties
Property: Function:
Position The Transform’s position in X, Y, and Z coordinates.
Rotation Rotation of the Transform in degrees around the X, Y,
and Z axes.
Scale The Transform’s scale along the X, Y, and Z axes. The
original size is represented by the value “1.” (The size at
which the object was imported).
Transform Editing
Transforms can be controlled in three-dimensional (3D)
space along the X, Y, and Z axes or two-dimensional (2D)
space along the X and Y axes. These axes are represented in
Unity by the colors red, green, and blue, respectively.
Transforms can be modified in the Scene View or by
changing their attributes in the Inspector. Transforms in
the scene may be modified using the Move, Rotate, and
Scale tools. These tools may be found in the Unity Editor’s
top left-hand corner.
The tools are applicable to any item in the scene. When
we click on an object, the tool gizmo will appear within it.
The look of the gadget is determined by the tool picked.
When we click and drag on one of the three gizmo axes,
its color will be yellow. The item will translate, rotate, or
scale along the specified axis as we move the mouse. When
we release the mouse button, the axis remains selected.
98 ◾ Mastering Unity
Parenting
When utilizing Unity, one of the most fundamental things
to grasp is parenting. When a GameObject is the Parent
of another GameObject, the Child GameObject moves,
rotates, and scales the same way as its Parent. Parenting
may be compared to the interaction between our arms
and our body; anytime our body moves, our arms move
as well. Child items can have their children, and so on.
So our hands may be seen as “children” of our arms, with
each hand having numerous fingers, and so on. There can
be several offspring for each item, but only one parent.
These several layers of parent–child interactions form a
Transform hierarchy.
The root is the object at the very top of a hierarchy (e.g.,
the only item in the hierarchy that does not have a parent).
Drag any GameObject in the Hierarchy View onto
another to create a Parent. The two GameObjects will form
a Parent–Child connection as a result of this.
It’s worth noting that the Transform values in the
Inspector for any child GameObject are displayed relative
to the Transform values of the Parent. These values are
known as local coordinates. Returning to the analogy of
the body and arms, our body’s position may change while
Working with Scenes and GameObjects ◾ 99
Scale’s Importance
The Transform scale defines the difference in size between
a mesh in your modeling application and a mesh in Unity.
The size of the mesh in Unity (and hence the scale of the
Transform) is critical, especially during physics model-
ing. The physics engine thinks that one unit in world space
equals one meter by default. If an item is particularly enor-
mous, it may appear to fall in “slow-motion”; the simula-
tion is accurate since we see a vast thing fall a long distance.
The size of our item can be affected by three factors:
Component Transformation
In Unity, every GameObject has a Transform component.
This component specifies the location, rotation, and scale
of the GameObject in the game world and Scene view. This
component cannot be removed.
The Transform component also supports the idea of
parenting, which allows us to make a GameObject a child
of another GameObject and control its position using the
Transform component of the parent. This is a critical com-
ponent of working with GameObjects in Unity.
Adding Components
The Components menu allows us to add Components
to the specified GameObject. We’ll give it a shot now
by attaching a Rigidbody to the empty GameObject
we just made. Select it and then go to the Component->
Physics->Rigidbody menu. When we do this, the
Rigidbody’s characteristics will display in the Inspector.
We can receive a surprise if you press Play while the empty
GameObject is still chosen. Try it out and note how the
Rigidbody has given the otherwise empty GameObject
functionality. (The GameObject’s transform’s Y position
begins to decrease. This is due to Unity’s physics engine
forcing the GameObject to fall under gravity.)
104 ◾ Mastering Unity
Property Experimentation
While our game is in Play Mode, we may alter any
GameObject’s attributes in the Inspector. For example, we
might wish to experiment with different leaping heights. If
we add a Jump Height attribute to a script, we may test it by
entering Play Mode, changing the value, and pressing the
jump button to see what occurs. Then, without leaving Play
Mode, we may make another modification and see the con-
sequences in seconds. When we quit Play Mode, our prop-
erties will restore to their pre-Play Mode settings, ensuring
no effort is lost. This method provides impressive flexibility
to explore, tweak, and perfect your gameplay without com-
mitting to lengthy iteration cycles.
Working with Scenes and GameObjects ◾ 107
Cube
This is a basic cube with one-unit-long sides that are tex-
tured such that the picture repeats on each of the six faces.
A cube isn’t a particularly frequent object in most games as
it is, but when scaled, it may be beneficial for walls, posts,
boxes, steps, and other similar objects. It is also a help-
ful placeholder object for programmers to utilize during
development when a completed model is unavailable. An
automobile body, for example, can be crudely recreated
using an extended box of nearly the proper size. Although
this isn’t appropriate for the entire game, it works well as
a small symbolic object for testing the car’s control code.
Because the edges of a cube are one unit long, we may
examine the proportions of a mesh imported into the scene
by placing a cube nearby and comparing the sizes.
Sphere
This is a unit diameter (0.5 unit radius) sphere that has been
textured such that the entire picture revolves around once,
108 ◾ Mastering Unity
with the top and bottom “pinched” at the poles. Spheres are
clearly helpful for portraying balls, planets, and missiles,
but a semi-transparent sphere may also be used to show
the radius of an effect in a graphical user interface (GUI).
Capsule
A capsule is a cylinder with two hemispherical covers on
either end. The item has a diameter of one unit and a height
of two units. It’s textured such that the picture loops around
precisely once, squeezed at the apex of each hemisphere.
While there aren’t many real-world things with this form,
the capsule is a handy prototype placeholder. For specific
activities, the mechanics of a rounded item are sometimes
superior to those of a box.
Cylinder
This is a primary two-unit-high and one-unit-diameter
cylinder that has been textured such that the image wraps
once around the tube form of the body but also appears
independently in the two flat, circular ends. Cylinders help
make posts, rods, and wheels but keep in mind that the col-
lider’s form is a capsule (there is no primitive cylinder col-
lider in Unity). If you require an exact cylindrical collider for
physics purposes, you should generate a mesh of the proper
shape in a modeling application and attach a mesh collider.
Plane
This is a flat square with ten-unit-long edges aligned in
the local coordinate space’s XZ plane. It’s textured such
that the entire image only displays once within the square.
Most flat surfaces, such as floors and walls, benefit from
Working with Scenes and GameObjects ◾ 109
Quad
The quad primitive is similar to the plane, except its edges
are only one unit long, and the surface is orientated in the
local coordinate space’s XY plane. In addition, a quad is
made up of only two triangles, whereas a plane has two
hundred. A quad is proper when a scene object is only uti-
lized as a display screen for an image or video. Quads may
be used to create simple GUI and information displays and
particles, sprites, and “impostor” graphics that stand in for
solid objects when viewed from a distance.
Primitive 2D GameObjects
Unity includes 2D Primitive GameObjects to let us quickly
prototype our Project without importing our Assets. To
make 2D primitive, navigate to GameObject > 2D Object >
Sprites and choose one of the following options:
• Square.
• Circle.
• Nine-Sliced.
• Isometric Diamond.
• Capsule.
• Hexagon Point-Top.
• Hexagon Flat-Top.
110 ◾ Mastering Unity
Square
The Square 2D primitive is a white square with a dimen-
sion of 1 × 1 Unity units. We may use it to build platforms
rapidly or as a placeholder for other items such as barriers
such as crates. We may interact with other GameObjects
and 2D physics by adding the Box Collider 2D component
to the GameObject. Select the Nine-Sliced option instead
for a more scalable Sprite that resizes dynamically.
Circle
The Circle 2D primitive is a white circle with a diameter
of one Unity unit. It may be used as a placeholder for vari-
ous objects in our Scene, such as obstacles or props such as
pick-ups or power-ups. We may use the Circle Collider 2D
to interact with other objects and 2D physics by adding it
to the GameObject.
Capsule
The Capsule 2D primitive is a white capsule with a size of
1 × 2 units. This Capsule can be used as a placeholder for
many aspects of our scene, such as an obstacle, an object,
or a character stand-in. We may interact with other objects
and 2D physics by adding a Capsule Collider 2D to the
GameObject.
Working with Scenes and GameObjects ◾ 111
Isometric Diamond
The Isometric Diamond 2D primitive is a 1 × 0.5 unit white
diamond-shaped Sprite. This Sprite is intended to act as a
placeholder for Isometric Tilemaps. To optimize tiling,
the pixels at the top and bottom of this Sprite have been
chopped significantly.
Flat-Top Hexagon
The Hexagon Flat-Top 2D primitive is a regular hexagon
with sides to the top and bottom 1 unit wide. It’s intended to
be used as a basic Sprite placeholder for Tiles in Hexagonal
Flat-Top Tilemaps. On optimize tiling, the pixels to the left
and right of this Sprite have been chopped significantly.
Point-Top Hexagon
The Hexagon Point-Top 2D primitive is a one-unit-tall
regular hexagon with points at the top and bottom. It’s
intended to be used as a basic Sprite placeholder for Tiles
in Hexagonal Pointed-Top Tilemaps. To optimize tiling,
the pixels at the top and bottom of this Sprite have been
chopped significantly.
Nine-Sliced
The Nine-Sliced 2D primitive is a white 1 × 1 unit square
with rounded corners. This Sprite has been nine-sliced,
with 64-pixel boundaries on each side. It is intended
for use with the Sprite Renderer’s Sliced and Tiled draw
modes. The nine-sliced Sprite may be used as a versatile
placeholder for numerous items in our Scene and Project.
To make the Sprite interact with other objects and 2D
physics, add a Box Collider 2D with Auto Tiling enabled.
112 ◾ Mastering Unity
Deactivating GameObjects
To remove a GameObject from the Scene momentarily,
label it as inactive. To do so, go to the Inspector and
uncheck the checkbox next to the GameObject’s name or
use the SetActive method in the script. Check the active-
Self attribute in the script to see if an object is active or
inactive.
Tags
A Tag is a term that may be assigned to one or more
GameObjects. We might, for example, create “Player” Tags
for player-controlled characters and “Enemy” Tags for
non-player-controlled characters. A “Collectable” Tag can
be used to identify things that the player can gather in a
Scene.
Tags aid in the identification of GameObjects for script-
ing reasons. They eliminate the need to manually add
GameObjects to a script’s public attributes through drag
and drop, saving time when utilizing the same script code
in several GameObjects.
Tags are essential in Collider control scripts for deter-
mining if the player is interacting with an opponent, a
prop, or a collectible, for example.
We may find a GameObject by instructing the
GameObject.FindWithTag() method to seek for any
object that contains the desired Tag. GameObject is used
in the following example: FindWithTag(). It creates the
114 ◾ Mastering Unity
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public GameObject respawnPrefab;
public GameObject respawn;
void Start()
{
if (respawn = = null)
respawn = GameObject.
FindWithTag("Respawn");
Instantiate(respawnPrefab, respawn.
transform.position, respawn.transform.
rotation) as GameObject;
}
}
Using a Tag
The Inspector displays the Tag and Layer drop-down
choices directly below the name of any GameObject. To
apply an existing Tag to a GameObject, enter the Tags
Working with Scenes and GameObjects ◾ 115
menu and select the desired Tag. This Tag is now con-
nected with the GameObject.
Property: Function:
Nothing Do not include the GameObject in any system’s
precomputations.
Everything Include the GameObject in the
precomputations for all of the systems listed
below.
Contribute GI While we enable this parameter, Unity takes
the target Mesh Renderer into account when
calculating global illumination. These
computations are done during the baking
period when lighting data is being
precomputed. The ContributeGI property
exposes the ReceiveGI property. The
ContributeGI feature has no impact unless
we activate a global illumination option for
the target Scene, such as Baked Global
Illumination or Realtime Global
Illumination. This flag is described in detail
in a Unity Blog post regarding static lighting
using lightprobes.
Occluder Static In the occlusion culling system, mark the
GameObject as a Static Occluder.
Occludee Static In the occlusion culling mechanism, mark the
GameObject as a Static Occludee.
Batching Static Combine the Mesh of the GameObject with
other suitable Meshes to potentially
minimize runtime rendering costs.
Navigation Static When precompiling navigation data, include
the GameObject.
Off Mesh Link When precomputing navigation data, try to
Generation construct an Off-Mesh Link that begins with
this GameObject.
Reflection Probe Include this GameObject in the precomputed
data for Reflection Probes with the Type
attribute set to Baked.
Working with Scenes and GameObjects ◾ 117
Project-Wide Modifications
Project-wide modifications in Unity affect the whole Project
rather than a single Scene. Go to File > Save Project to save
Project-wide settings without storing Scene modifications.
118 ◾ Mastering Unity
Input: InputManager.asset
Player: ProjectSettings.asset
Tags And Layers: TagManager.asset
Time: TimeManager.asset
Physics: DynamicsManager.asset
Graphics: GraphicsSettings.asset
Physics 2D: Physics2DSettings.asset
Quality: QualitySettings.asset
Editor: EditorUserSettings.asset
Network: NetworkManager.asset
Audio: AudioManager.asset
Immediate Saving
When certain modifications occur, Unity quickly saves
them to disc. These are some examples:
PREFABS
The Prefab system in Unity allows us to build, config-
ure, and save a GameObject as a reusable Asset, replete
with all of its components, property values, and child
GameObjects. The Prefab Asset serves as a template for
creating new Prefab instances in the Scene.
Converting a GameObject set in a certain way—such as
a non-player character (NPC), prop, or piece of scenery—
to a Prefab allows us to reuse it in numerous places in our
Scene or across several Scenes in our Project. This is pref-
erable to copying and pasting the GameObject since the
Prefab system automatically keeps all copies in sync.
Any changes we make to a Prefab Asset are instantly
mirrored in all instances of that Prefab, allowing us
to make broad changes throughout our whole Project
without making identical changes to each copy of the
Asset.
Prefabs may be nestled inside other Prefabs to construct
complicated object hierarchies that are straightforward to
change at numerous levels.
This does not, however, imply that all Prefab instances
must be similar. If we want certain Prefab instances to be
different from others, we may override settings on specific
prefab instances. We may also construct Prefab variations,
which allow us to organize a collection of overrides into a
meaningful version of a Prefab.
Prefabs are particularly useful when we wish to cre-
ate GameObjects during runtime that did not exist in
our Scene at the start, such as making powerups, special
effects, projectiles, or NPCs appear at the appropriate time
points throughout gameplay.
Working with Scenes and GameObjects ◾ 121
Prefabs Creation
Prefab Assets serve as templates in Unity’s Prefab system.
Prefab Assets are created in the Editor and stored as an
asset in the Project window. Prefab Assets may be used
to build an unlimited number of Prefab instances. Prefab
instances may be produced in the editor and stored as part
of Scenes, or they can be instantiated during runtime.
Isolation Editing
In Prefab Mode, we may start editing a Prefab in a variety
of ways. We may open a Prefab Asset and change it sepa-
rately in the following ways:
Contextual Editing
We may also open a Prefab Asset in Context by using an
instance of that Prefab. There are several ways to accom-
plish this, including:
In the Inspector window, choose a Prefab instance from
the Hierarchy pane and click the Open button.
In the Hierarchy pane, choose a Prefab instance and hit
P on the keyboard. This is the standard keyboard binding.
In the Hierarchy pane, click the arrow button next to the
Prefab instance.
Unity shows the visual representation of the context in
grey scale by default to visually separate it from the Prefab
contents you change. However, we can utilize the Prefab bar’s
Context: control to change it to any of the following states:
Save Automatically
In the upper right corner of the Scene view, an Auto Save is
setting for Prefab Mode. When we activate it, Unity stores
126 ◾ Mastering Unity
Undo
When we make changes to a Prefab Asset while it is in
Prefab Mode, you can only undo those changes while it
is still in Prefab Mode. When we quit Prefab Mode for a
Working with Scenes and GameObjects ◾ 127
Dropdown Overrides
The Customizations drop-down pane displays all of the
Prefab instance’s overrides. It also allows us to add instance
overrides to the Prefab Asset or revert instance overrides to
the Prefab Asset’s values. The Overrides drop-down but-
ton shows only for the root Prefab instance, not for Prefabs
inside Prefabs.
The Overrides drop-down box allows us to apply or
revert individual prefab overrides or to apply or revert all
prefab overrides at once.
Menus in Context
Instead of utilizing the Overrides drop-down window,
you may rollback and apply specific overrides using the
Inspector’s context menu.
132 ◾ Mastering Unity
Prefab Variations
Prefab Variants come in handy when we need a collection
of predefined versions of a Prefab.
For example, we could wish to include a variety of
GermSlimeTargets in our game, all of which are built on
the same core GermSlimeTarget Prefab. However, we may
want some GermSlimeTargets to carry objects, travel at
various speeds, or produce additional sound effects.
To do this, we might configure our first GermSlimeTarget
Prefab to execute all of the core activities that all
GermSlimeTarget should share and then construct numer-
ous Prefab Variants to:
that it does not delete the Prefab Asset and just impacts the
Prefab instance.
Unpacking a Prefab instance is as simple as right-click-
ing on it in the Hierarchy and selecting Unpack Prefab. The
generated GameObject in the Scene is no longer linked to
its previous Prefab Asset. This procedure does not affect
the Prefab Asset itself, and there may still be instances of it
in our Project.
If we override your Prefab instance before unpacking it,
they will be “baked” onto the resultant GameObjects. That
is, the values will remain unchanged, but they will no lon-
ger have the status as overrides since there is no Prefab to
override.
When we unpack a Prefab containing nested Prefabs,
the nested Prefabs continue to be Prefab instances with
connections to their respective Prefab Assets. Similarly,
when we unpack a Prefab Variant, a new Prefab instance
is created at the root that is an instance of the basic Prefab.
In general, unpacking a Prefab instance returns the
same items that we see when we enter Prefab Mode for that
Prefab. This is due to the fact that Prefab Mode displays
the contents of a Prefab, and unpacking a Prefab instance
unpacks the contents of a Prefab.
If we wish to replace a Prefab instance with normal
GameObjects and delete any ties to any Prefab Assets,
right-click on it in the Hierarchy and select Unpack Prefab
Completely. This is identical to unpacking the Prefab and
continuing to unpack any Prefab instances that occur due
to being nested or base Prefabs.
Prefab instances that reside in Scenes or inside other
Prefabs can be unpacked.
Working with Scenes and GameObjects ◾ 141
• In a Nutshell:
• Rigidbody Element: This component is in charge
of applying physics simulations to GameObjects
such as Gravity and attributes such as Mass and
Velocity. It is a necessary component in identi-
fying collisions. In Unity, there are two sorts of
Rigidbody Components: 3D and 2D. It is critical
to choose the appropriate one for the kind of set-
ting in which you operate.
• Collider Component: Consider this component
to be the volume of space that our item occupies.
Colliders provide a method for registering colli-
sions between objects in the scene. They come in
a variety of forms and sizes to suit our needs. The
Collider, like the Rigidbody, must be chosen cor-
rectly for Unity to detect collisions accurately. If
we’re working in 3D, ensure sure our GameObjects
aren’t accidentally utilizing 2D Colliders. Fortunately,
all Colliders are labeled explicitly.
142 ◾ Mastering Unity
Physics
Unity allows us to simulate physics in our project to verify
that objects accelerate and behave appropriately to colli-
sions, gravity, and other forces. Unity has many physics
engine implementations that we may utilize depending
on the demands of our project: 3D, 2D, object-oriented, or
data-oriented.
Working with Scenes and GameObjects ◾ 143
• 3D physics built-in.
• There is built-in 2D physics.
2D Physics Reference
Use the above attributes as global settings for Physics 2D. If
we wish to manage the global 3D physics parameters, use
the Physics Manager settings instead.
144 ◾ Mastering Unity
Animation in Unity
Clips of Animation
Animation Clips are a key component of Unity’s anima-
tion system. Unity allows for the import of animation from
other sources and creating animation clips from scratch
within the editor through the Animation window.
Animation in Unity ◾ 149
Overview
When Unity imports Model files containing Humanoid
Rigs and Animation, it must reconcile the Model’s bone
structure to its Animation. It accomplishes this by map-
ping each bone in the file to a Humanoid Avatar so that
the Animation may be correctly played. Because of all this,
Animation in Unity ◾ 153
Avatar Setup
Set the Animation Type to Humanoid on the Inspector
window’s Rig tab. The Avatar Definition attribute is set
to Create from This Model by default. If we preserve this
option, Unity will attempt to map the set of bones described
in the file to a Humanoid Avatar.
In certain circumstances, we may alter this option to
Copy From Other Avatar to utilize an Avatar we’ve already
created for another Model file. For example, suppose we
construct a Mesh (skin) in our 3D modeling application
with multiple individual animations. In that case, you may
export the Mesh to a single FBX file and each animation to
a separate FBX file. When importing these files into Unity,
we need to make one Avatar for the first file (usually the
Mesh). We may reuse that Avatar for the rest of the files as
long as they all utilize the same bone structure (for exam-
ple, all the animations).
Animation in Unity ◾ 155
Strategy Mapping
If the model does not produce a proper match, we can use
a similar procedure to the one Unity employs:
Outline
When we import a Generic model into Unity, we must
specify which bone is the Root node. This effectively deter-
mines the center of mass of the model.
Generic setups do not use the Humanoid Avatar win-
dow since there is only one bone to map. Consequently,
preparing to import a non-humanoid model file into Unity
needs fewer steps than preparing a humanoid model.
Scene
Property Function
Scale Factor When the original file scale (from the Model
file) does not meet the specified scale in your
Project, set this value to apply a global scale to
the imported Model, the physics system in
Unity expects 1 meter in the game world to
equal 1 unit in the imported file.
Convert Units Enabling this option causes the Model scaling
defined in the Model file to be converted to
Unity’s scale.
Bake Axis When we import a Model that utilizes a different
Conversion axis system than Unity, enable this feature to
bake the results of axis conversion directly into
our application’s Asset data (for example, vertex
or animation data). Disable this parameter to
adjust the root GameObject’s Transform
component at runtime to mimic axis conversion.
Import Allow Unity to import blend shapes with our
BlendShapes Mesh by enabling this feature. For further
information, see Importing blend shapes.
Import Visibility Import the FBX parameters that determine
whether MeshRenderer components are
enabled or not (visible).
(Continued)
Animation in Unity ◾ 165
Property Function
Import Cameras Cameras from our .FBX files can be imported.
Import Lights Lights from our .FBX file should be imported.
Preserve Hierarchy Even if this model only has one root, always
generate an explicit prefab root. As an
optimization tactic, the FBX Importer usually
removes any empty root nodes from the model.
If we have multiple FBX files with different
parts of the same hierarchy, we may use this
option to keep the original structure.
File1.fbx, for example, has a rig and a Mesh, but
file2.fbx contains the same rig but simply the
animation for that rig. If we import file2.fbx
without checking this box, Unity removes the
root node, the hierarchies do not match, and
the animation breaks.
Sort Hierarchy By Enable this feature to rank GameObjects inside
Name the hierarchy alphabetically. To keep the
hierarchical order defined in the FBX file,
disable this parameter.
Visibility Importing
The Import Visibility feature in Unity may read visibil-
ity properties from FBX files. By adjusting the Renderer.
enabled property, values and animation curves can acti-
vate or disable MeshRenderer components.
Visibility inheritance is enabled by default, although it
may be disabled. For example, if a parent Mesh’s visibility
is set to 0, all children’s renderers are similarly disabled. In
this scenario, one animation curve is constructed for each
Renderer.enabled parameter of the child.
Some 3D modeling software does not support or have
restrictions on visibility attributes. More information may
be found at:
Cameras Importing
When importing Cameras from an .FBX file, Unity supports
the following properties:
Property Function
Projection mode Perspective or orthographic. Animation is
not supported.
Field of View Animation is supported.
All Physical Camera When we import a Camera with Physical
characteristics Properties (for example, from Maya),
Unity builds a Camera with the Physical
Camera attribute enabled and the values
from the FBX file for Focal Length,
Sensor Type, Sensor Size, Lens Shift, and
Gate Fit.
Near and Far Clipping On these settings, Unity does not import
Plane distance any animation. Enable the Clip Manually
setting when exporting from 3ds Max;
otherwise, the default settings are used
on import.
Target Cameras When importing a Target Camera, Unity
constructs a camera with a LookAt
constraint that uses the source as the
target object.
Light Import
The following light kinds are supported:
• Spot.
• Omni.
• Area.
• Directional.
168 ◾ Mastering Unity
Property Function
Range If UseFarAttenuation is enabled, the
FarAttenuationEndValue is utilized. Animation is
not supported by FarAttenuationEndValue.
Color Animation is supported.
Intensity Animation is supported.
Spot Angle Animation is supported. Spot lights are the only ones
that have this option.
Restrictions
Scaling on light characteristics is used in several 3D mod-
eling applications. For example, we may change the light
cone by scaling a spot light based on its hierarchy. Because
Unity does not perform this, lighting may seem different
in the game.
The width and height of area lights are not defined in
the FBX format. Some 3D modeling software lacks this fea-
ture and must rely on scaling to determine the rectangular
region. As a result, when imported, area lights always have
a size of 1.
Targeted light animations aren’t supported unless
they’re baked.
Property Function
Animation Type Specify the animation style.
None There is no animation.
Legacy The Legacy Animation System should be used.
Import and utilize animations in the same way
as we did in Unity 3.x and before.
Generic If our rig is not humanoid, use the Generic
Animation System (quadruped or any entity
to be animated). Unity chooses a root node
for us, but we may specify another bone to
serve as the root node instead.
Humanoid If our rig is humanoid, use the Humanoid
Animation System (two legs, two arms, and a
head). Unity typically recognizes the skeleton
and accurately transfers it to the Avatar. In
some circumstances, we may need to update
the Avatar Definition and manually configure
the mapping.
Property Function
Avatar Definition Select where we want to acquire the Avatar
definition.
Create from this Create an Avatar with this model.
model
Copy from Other Point to an Avatar that has been set up on another
Avatar model.
Root Node Choose a bone to serve as the Avatar’s root node.
This option is only accessible if the Avatar
Definition is set to Create From This Model.
Source Import animation clips from another Avatar
with the same setup.
If the Avatar Definition is set to Copy from Other
Avatar, this feature is only available.
Skin Weights Set a maximum number of bones that can
influence a single vertex.
Standard Use a maximum of four bones to exert maximum
(4 Bones) influence. This is the default option and is
preferred for best results.
Custom Set our limit for the number of bones.
The Max Bones/Vertex and Max Bone Weight
attributes appear when we pick this option.
Max Bones/ Set the maximum number of bones that a
Vertex specific vertex can influence. We can specify one
to 32 bones per vertex; however the more
bones we utilize to impact a vertex, the higher
the performance penalty.
This option is only accessible if the Skin Weights
parameter is set to Custom.
(Continued)
Animation in Unity ◾ 171
Property Function
Max Bone Weight Set the lower limit for taking into account bone
weights. The weighting formula disregards
anything less than this number, and Unity
ramps up bone weights more than this value to
a total of 1.0.
Only if the Skin Weights attribute is set to
Custom is this option available.
Optimize Game Remove and save the imported character’s
Object GameObject Transform hierarchy in the Avatar
and Animator component. When enabled, the
character’s SkinnedMeshRenderers utilize the
internal skeleton of the Unity animation
system, which increases the performance of
animated figures.
If the Avatar Definition is set to Create From
This Model, this option is only available.
Extra Transforms When Optimize Game Object is enabled, we
to Expose may specify which Transform routes Unity
should disregard. See Including Extra
Transforms for further details.
This section is only shown if Optimize Game
Object is enabled.
• Head.
• Right Arm.
• Left Arm.
• Right Hand.
• Left Hand.
• Right Leg.
• Left Leg.
• Root.
176 ◾ Mastering Unity
Selection of a Transform
If our animation does not employ a Humanoid Avatar,
or if we want more control over which specific bones are
masked, we can pick or deselect elements of the Model’s
hierarchy:
Timeline of Animation
The timeline for the current clip is shown on the right side
of the Animation View. This timeline displays the key-
frames for each animation property. The timeline view
is available in two modes: Dopesheet and Curves. Go to
the bottom of the animated property list area and click
Dopesheet or Curve to switch between these modes.
These provide two different perspectives on the
Animation timeline and keyframe data.
Window Locking
We may prevent the Animation editor window from
automatically switching to reflect the currently chosen
GameObject in the Hierarchy or Scene by locking it.
Locking the window is essential if we want to concentrate
on the Animation of one GameObject while still selecting
and manipulating other GameObjects in the Scene.
Keyframes Recording
Click the Animation Record button to start recording
keyframes for the selected GameObject. This activates
Animation Record Mode, which records changes to the
GameObject into the Animation Clip.
Once in Record mode, we may add keyframes by drag-
ging the white Playback head to the desired time on the
Animation time line and then modifying our GameObject
to the correct state at that point in time.
Changes to the GameObject are saved as keyframes at
present, shown by the white line in the Animation Window.
Any modification to an animatable property (such as its
position or rotation) will result in the appearance of a key-
frame for that property in the Animation window.
Selecting or dragging in the time line bar changes the
playback head and displays the status of the animation at
the current time of the playback head.
The Animation window is seen in record mode. The
time line bar has a red tint, indicating that it is in record
mode, and the animation properties have a red backdrop
in the inspector.
By pressing the Record button again, we can exit the
Record Mode at any moment. When we exit Record mode,
the Animation window transitions to Preview mode,
allowing us to see the GameObject at its current position
along the animation time line.
186 ◾ Mastering Unity
Time Line
We may shift the playback head to any frame on the
Animation window time line by clicking anywhere and
then previewing or adjusting that frame in the Animation
Clip. The numbers on the time line are shown in sec-
onds and frames; thus, 1:30 equals one second and thirty
frames.
• Keyboard shortcuts:
• K: Key all animated. Adds a keyframe for all ani-
mated properties in the animation window at the
current location of the playback head.
• Shift-K: Modify all keys. Only adds a keyframe
for animated properties that have been changed
at the current location of the playback head in the
animation window.
Audio
Full 3D spatial sound, real-time mixing and mastering,
mixer hierarchies, snapshots, preconfigured effects, and
many more capabilities are available in Unity Audio. This
includes in-game sounds as well.
That said, we will turn our attention to Performance
Optimization in the next chapter.
Chapter 5
Scene Performance
Optimization
DirectX
Navigate to the Player settings (menu: Edit > Project Settings,
then choose the Player category) and select DirectX11
as our chosen Graphics API in the Editor or Standalone
Player. Disable the Auto Graphics API for Windows setting
and select DirectX11 from the drop-down menu.
Shaders for the Surface
Because some sections of the Surface Shader compilation
pipeline do not comprehend DX11-specific HLSL syntax,
Scene Performance Optimization ◾ 195
Shaders Computed
Compute Shaders are graphics card-based programs that
can speed up rendering.
Metal
Metal is Apple’s industry-standard graphics API. Unity
works with Metal on iOS, tvOS, and macOS (Standalone
and Editor).
On Apple systems, Metal provides more features than
OpenGL ES.
Metal has the following advantages:
Metal Enabling
To set Metal the default graphics API for the Unity Editor
and Standalone Player, perform one of the following:
Core OpenGL
OpenGL Core is a backend that can handle the most recent
OpenGL capabilities on Windows, macOS X, and Linux.
Depending on the OpenGL driver support, this ranges
from OpenGL 3.2 to OpenGL 4.5.
OpenGL Specifications
The following are the minimal requirements for OpenGL
Core:
the CPU. Because tactics for optimizing for GPU vs. CPU
are generally different (and might even be contrary—for
example, it’s fairly usual to make the GPU do more work
when optimizing for CPU, and vice versa), the first rule
of any optimization is to discover where the performance
problem is.
Common bottlenecks and how to detect them:
CPU Enhancement
To render things on the screen, the CPU must conduct con-
siderable processing work, such as detecting whether lights
effect that object, establishing the shader and shader param-
eters, issuing drawing orders to the graphics driver, and
preparing the commands for graphics card transmission.
All of this “per object” CPU utilization is resource-
intensive, and it may pile up if you have a lot of visible
items. For example, if we have a thousand triangles, it is
much easier on the CPU, and they’re all in one mesh rather
than one mesh per triangle. The cost of both cases on the
GPU is roughly comparable, but the CPU effort required to
render a thousand items is much greater.
Reduce the number of visible objects. To minimize the
amount of work the CPU must perform:
Combine items such that each mesh has at least a few hun-
dred triangles, and just one Material is used for the whole
mesh. It’s worth noting that joining two things that don’t
share a substance yields any performance boost. The most
common cause for requiring multiple materials is that two
models do not share the same textures, ensure that any
objects you combine have the same textures to improve
CPU efficiency.
Combining objects may not make sense when utilizing
many pixel lights in the Forward rendering process.
Lighting Efficiency
The quickest method is to produce lighting that does
not require any computation at all. To do this, utilize
Lightmapping to “bake” static lighting once rather than
compute it per frame. The process of creating a light-
mapped environment in Unity takes only a bit longer than
simply adding a light in the area, but:
required by the shadow pass are the same. Many crates, for
example, might employ Materials with different Textures on
them, but the textures are irrelevant for shadow caster draw-
ing; therefore, they can be batched together in this scenario.
Dynamic Batching
If two GameObjects have the same Material and meet addi-
tional requirements, Unity can automatically batch move
them into the same draw call. Dynamic batching occurs
automatically and requires no further effort on our part.
Instancing of GPUs
Using a limited number of draw calls, use GPU Instancing
to draw (or render) several copies of the same Mesh simul-
taneously. This is handy for sketching items that recur regu-
larly in a Scene, such as houses, trees, grass, or other things.
Each draw call merely produces identical Meshes, but
each instance might have various parameters (for example,
color or size) to add diversity and lessen the perception of
repetition.
GPU Instancing has the potential to minimize the
number of draw calls utilized per Scene. This dramatically
increases our project’s rendering performance.
Scene Performance Optimization ◾ 217
Statistics
Statistics Description
FPS Updates to the frame per second, Unity
performs.
CPU The overall amount of time required to process
one frame. This includes the time Unity took
to execute our application’s frame update and
the time Unity spent in the Editor updating
the Scene view, other Editor Windows, or
other Editor-only operations.
Rendering time: The number of times it takes
to render one frame. This figure includes the
time Unity took to render the Game View,
but not the time Unity used in the Editor to
render the Scene View or create the
Inspector.
Batches The total number of batches processed by
Unity during a frame. This figure contains
both static and dynamic batches, as well as,
for instance, batches.
Saved by batching The total number of batches created by Unity.
Share materials across distinct GameObjects
as often as feasible to guarantee optimal
batching. Changing the rendering state
divides batches into groups that have the
same state.
Tris The amount of triangles processed by Unity
during a frame. This is especially true when
optimizing for low-end hardware.
Verts The number of vertices processed by Unity
during a frame. This is especially true when
optimizing for low-end hardware.
Screen The screen’s resolution, as well as the quantity
of RAM it employs.
(Continued)
Scene Performance Optimization ◾ 219
Statistics Description
SetPass The number of times Unity changes between
shader passes while rendering GameObjects
during a frame. A shader can have several
shader passes, each of which renders
GameObjects in the scene differently. Each
pass necessitates the binding of a new shader,
which may result in CPU cost.
Shadow casters The number of GameObjects in the frame that
throw shadows.
Visible skinned Unity rendered the amount of Skinned Mesh
meshes Renderers in the frame.
Animations The amount of animations that are active
throughout the frame.
To Begin With
To enable Mip Map Streaming, navigate the Quality
Settings in Unity (Edit > Project Settings > Quality) and
tick the Texture Streaming checkbox. This displays the
Mip Map Streaming system’s options.
Then, for each Texture, activate Mip Map Streaming to
allowing the Mip Map Streaming system to stream each
Texture’s mip maps from the disc into memory. To do so,
choose the Texture to which we wish to apply Mip Map
Streaming, then go to the Inspector window and look at
the Texture Import settings. Enable the Streaming Mip
Maps option in the Advanced settings.
Scene Performance Optimization ◾ 223
Using the Debugging API, we can also create our own debug
tools and visualizations.
Chapter 6
Completing
the Game
• Rider by Jetbrains.
• Code in Visual Studio.
Editor Debugging
We can debug the C# code that is running in the Unity
Editor while it is in Play Mode.
To debug in the Editor, change the Editor’s Code
Optimization mode to Debug Mode, then attach a code
editor with debugging capabilities.
To change the Code Optimization mode, click the
Debug button in the Unity Editor Status Bar’s bottom right
corner.
Void Start()
{
Debug.Log("Debug message");
}
}
In-Player Debugging
To analyze script code running in a Unity Player, first select
the “Development Build” and “Script Debugging” options
232 ◾ Mastering Unity
TESTING OF UNITS
As our project develops in size and the number of scripts,
classes, and methods grow, it can be challenging to verify
that a change in one section of our code does not break
things in another.
Automated testing allows us to ensure that all elements
of our code are working correctly. It saves time by identi-
fying where and when problems arise as soon as they are
introduced during development instead of depending on
manual testing or, worse, bug reports from our end users.
The Unity Test Framework package is a tool that allows
us to test our code in both Edit and Play modes and on
target platforms, including Standalone, Android, and iOS.
Appraisal
A creating keyframes in
preview mode, 187
Account creation of Unity,
keyframes recording,
32–33
185–186
Add Component, 35
making keyframes by
Ahead-of-time (AOT)
manually, 187–188
compilation, 14
time line, 187
Android and iOS device
humanoid movements
debugging, 232
addition to a model,
Animation, 145
152
Avatar Mapping tab, 171
Avatar mask, making,
Avatar data saving and
157–158
reuse, 172
Avatar setup, 154–155
making use of Avatar
changing the pose, 157
masks, 173
configure the Avatar,
Avatar Muscle and Settings
155–156
tab, 173
strategy mapping, 156–157
changes being previewed,
Human Template Window, 177
174
importing animation files,
degree of freedom
151
translate, 174–175
legacy animation, system of,
Avatars with humanoid,
148
151–152
clips of animation, 148
controllers for animators, 188
externally sourced
externally sourced animation,
animation, 149
149–151
Unity to create and edit
GameObject, adding
the animation, 149
animation to, 184
247
248 ◾ Index
J M
JavaScript, 22 Mac, Visual Studio for, 228
JetBrains Rider, 228 MacOS OpenGL driver,
JIT compilation, see Just-in-time limitations of, 198
compilation Material in Unity, 70
Juego Studios, 7 Messages, 57
Just-in-time (JIT) compilation, Metal, 195
14 Metal API validation, 197
Metal enabling, 196–197
restrictions and requirements,
K
196
KeyCode variable, 52 Mip Map Streaming system, 221,
222
enabling, 222–223
L
mipmap streaming
Languages to be learned for troubleshooting,
Unity, 21 224–225
Boo, 22–23 restrictions, 223–224
C# programming language, troubleshooting, 224–225
21–22 for textures, 208
benefits of, 25–27 Model import settings dialogue
C/C++, 24 box, 162–163
IronPython, 23 Model tab, 163
Index ◾ 255
P adding, 134
developing a Prefab
Parent–Child connection, 98
variant, 135–136
Particle System in Unity, 71
Prefab variant editing,
Per-pixel lighting optimization,
136–138
207
Prefab variations, 135
Physics component, 48–49
using their instances, 134
Plane, 108–109
override, multiple layers of,
Play Mode, 82
138
Play mode function, 9
target selection, applying,
Polygon Collider 2D, 50
138–139
Prefab Editing in Prefab Mode,
overrides, 127
123
alignment of Prefab
changing from isolation to
instance, 129
context mode, 126
precedence given to,
contextual editing, 124–125
128–129
environment for editing, 127
physics, 142
isolation editing, 123–124
object-oriented projects
prefab mode entry and exit,
with built-in physics
123
engines, 143
save automatically, 125–126
for object-oriented tasks,
undo, 126–127
use 3D physics, 143
Prefabs, 50, 120
2D physics reference,
changing a occurrences of,
143–144
129
prefab instance unpacking,
dropdown overrides,
139–140
130–131
Unity3D fundamentals,
menus in context, 131–132
141–142
creation, 121
Prefab Variant, 135–136,
existing prefabs,
137–138
replacement of,
Preview Mode, 184–185
122–123
Project Window, 184, 240
prefab instance creation,
Pro tier, 11
122
Python, 23
prefabricated assets,
making, 121–122
Q
and instantiation in Unity,
50–52 Quad, 109
nested Prefabs, 132–133 Quality window parameters, 207
Index ◾ 257
R instancing of GPUs,
216–217
Record button, 185
streaming of Mip Maps,
Record Mode, 184
221–225
Rect tool, 39
Scenes, 73
Rect Transform, 63
creation, loading, and saving,
Render Mode, 207
74–77
RenderTexture, 220
multi-scene editing, 77
Rigidbodies and physics in
Lightmap data, baking, 80
Unity, 48–49
navmesh data, baking,
Rigidbody2D, 48
80–81
Rig tab, 155, 168
occlusion culling data,
generic animation, types of,
baking, 81
169–171
Play Mode, 82
Rotate tool, 39
scene-specific settings, 82
Rust, 24–25
scripting, 83
new scene settings, 93
S types settings by default,
94
Save Scene As option, 83
settings for the scene
Scaling tool, 39
template, 93
SceneManager class, 83
Scene saving and loading in
Scene performance optimization,
Unity, 41–42
193
SceneSetup class, 83
application programming
Scene templates, 84
interface (API) support
customizing the creation of
for graphics, 193
new scenes, 90–91
DirectX, 194–195
making a blank scene
Metal, 195–197
template, 85–86
OpenGL Core, 197–200
making a template
graphics performance
from an existing asset in a
optimizing, 200
scene, 86
displaying the statistics
out of the current scene,
window, 217–219
86–87
draw calls, batching of,
modifying, 87–89
211–216
sequence of scene template
find high-impact graphics,
instantiation, 91–93
200–211
Scene View, 239
Frame Debugger, 219–221
258 ◾ Index
Unity Editor V
reloading code in, 20
“Vase” Prefab, 138, 139
system requirements for, 12
Viewport, 35
UnityEngine Objects, 18, 19
Virtual reality (VR)
Unity IDE, 238
compatibility, 5
Unity Interface, 239–240
Visual Studio
Unity Player, system
for Mac, 228
requirements for, 12–13
for Windows, 228
Unity Profiler, 233
VR compatibility, see Virtual
Unity Test Framework package,
reality compatibility
235
VS Code, 229
Unity 3D game development, 4, 5
benefits of, 8
licensing, options for, 10–11 W
overall views, 11–12 Warning signals, 57
system requirements for Windows
Unity Editor, 12 for Avatar mask, 175
system requirements for humanoid body, choosing,
Unity Player, 12–13 175–176
User interface (UI) components, selection of transform, 176
39, 62–64, 190 locking, 182
choosing a UI system for our Visual Studio for, 228
project, 191 Working of Unity, 34–37
Immediate Mode Graphical
UI, 191
Y
toolkit for, 190–191
Unity UI package, 191 YAML file, 177