Unity doc reading notes (1) Working in Unity

上一篇博客结束,应该可以对Unity有个总体但是不深入不系统的理解,这次开始就从头系统得阅读官方文档来深入了解Unity的各种概念和功能。

Start reading Unity

Creating

Scene: Scene

Scenes are where you work with content in Unity. They are assets that contain all or part of a game or application. For example, you might create a simple game in a single scene, while for a more complex game, you might use a scene in each level, each with its own environment, characters, obstacles, decorations, and UI. You can create any number of scenes in a project. When you create a new project and open it for the first time, Unity opens a sample scene that only contains cameras and lights.

Create a new scene

There are three ways to create a new scene:

  • Using the Create Scene dialog box, you can choose to create a new scene from a template (File - > New Scene).
  • Use the menu to create a new scene directly from the current scene (Asset - > Create - > Scene)
  • Created using a script, the create statement will return a pointer to the new scene and trigger an event to create the scene. If there are cloned resources or dependencies in the scene template, you need to specify the path to save these resources.

Load scene

To open a scene, do one of the following:

  • In the Project window, double-click the scene resource.
    From the menu, select File > New Scene
  • From the menu, select File > Recent Scene > [NAME-OF-SCENE]

If your current scene contains unsaved changes, Unity will prompt you to save the scene or discard the changes.

Save scene

Simultaneous editing of multiple scenes

Unity - Manual: Multi-Scene editing

Multiple scenes can be opened for editing at the same time in the editor, but each scene must be saved separately when saving.

At present, it is not clear what the significance of this function is, that is, multiple scenes are put into the Hierarchy at the same time, and the specific editing is not much different from a single scene.

Scene

Unity uses scene templates to create new scenes. Scene templates are assets stored in the project. They are similar to scenes, but designed to be copied, not used directly.

Scene templates can be used for quick reuse of the same scene, or scripts can be used to create specific scenes based on the template.

Every time you create a new scene, Unity copies the scene template. You can think of a scene template as a pre-configured scene with everything you want to start. For example, the default Basic template usually contains a camera and a light. You can create your own scene template to customize the type of new scene you can create in your project. For example, you can create templates for every level in the game, so that everyone in the project can start their scene with the right assets and configurations. You can create templates from any Unity scene.

How to create scene templates

  • Create an empty template
  • Create a template from an existing scene
  • Create a template from the current scene
  • Use scripts to create templates (you can create empty templates, or create templates based on a certain scenario)

In the above process, unless creating an empty template, Unity will ask which resources or dependencies need to be copied instead of referenced.

It should be noted here that the copied resources are independent, and the referenced resources are common. If a referenced resource is mistaken for an independent modification, a bug may be introduced.

Edit Scene Template

Unity - Manual: Editing scene templates

  • Details: Specify the scene used by the template and include the template description that appears in the “New Scene” dialog box.
  • thumbnail: Provides the option to create a preview image for the template.
  • Scene Template Pipeline: Specifies an optional custom script to run when Unity creates a new scene from a template.
  • Dependencies Dependency properties: define the set of packages they require in their manifest. For projects, these are considered direct dependencies; for packages, these are indirect or transitive dependencies.

img

The creation process of custom scenes

In fact, every time a new scene is created, an instance is created from the scene template, so Unity provides us with the ability to resemble hooks or lifecycles during template instantiation.

When Unity instantiates a new scene from a template, to run the custom code, create a scene template pipeline script and connect it to the template. Every time you create a new scene from a template, Unity will also create a new instance of the pipeline script.

Unity - Manual: Customizing new scene creation

We can first define a Pipline (the ISceneTemplatePiplne interface must be declared).

img

Then bind to the scene template pipeline

GameObject

Unity - Manual: GameObjects

Game objects are the most important concept in the Unity editor. Every object in a game is a game object, from characters and collectible items to lights, cameras, and special effects. However, a game object cannot do anything by itself; before it becomes a character, environment, or special effect, you need to give it properties, aka Components.

Game objects are the basic objects that represent characters, props, and scenes in Unity. They don’t do much work by themselves, but they act as containers for components that implement functionality.

So GameObject is actually nothing to say, what it can do basically depends on what Components it has.

Transform

Unity - Manual: Transforms

Influence of father-son relationship

The Transform’s position, rotation, and scaling values are measured relative to the Transform’s parent object. If the Transform has no parent element, the properties are measured in world space.

When one GameObject is the parent of another GameObject, the child GameObjects move, rotate, and scale exactly the same as their parent.

Non-uniform scaling can cause some problems

Non-uniform scaling is when the x, y, and z values scaled in the transformation are different; for example (2,4,2). In contrast, uniform scaling has the same value for x, y, z; for example (3,3,3). Non-uniform scaling can be useful in some specific situations, but it introduces some strange phenomena that uniform scaling does not occur:

  • Some components do not fully support non-uniform scaling. For example, some components have a circular or spherical element defined by the Radius property, which includes Sphere Collider, Capsule Collider, Light, and Audio Source. In this case, the circle will not become an elliptical non-uniform scaling, as you would expect, will just remain circular.
  • When a child object has a non-uniformly scaled parent object and is rotated relative to that parent object, it may appear tilted or clipped. There are components that support simple non-uniform scaling, but don’t work properly when tilted like this. For example, a tilted Box Collider will not exactly match the shape of the rendered mesh.
  • For performance reasons, the child objects of a non-uniformly scaled parent object do not automatically update their scaling when rotated. Therefore, when the scale is finally updated (for example, if the child object is separated from the parent object), the shape of the child object may suddenly change.

The importance of scaling (the importance of size):

The scale of Transform determines the difference between the size of the mesh in your modeling application and in Unity. The size of the mesh is very important in Unity (and therefore the scale of the transform), especially in physics simulations. By default, the physics engine assumes that a unit in world space corresponds to 1 meter. If an object is very large, it looks like it will fall in slow motion; this simulation is actually correct because, in reality, what you are seeing is a very large object falling far away.

There are three factors that can affect the size of your object:

  • Size of the mesh in the 3D modeling application.

  • Set the mesh scale factor in the import settings of the object.

  • The scale values of your Transform Component.

Ideally, you should not scale your objects in the Transform component. The best option is to create realistic-scale models so you don’t have to change your Transform scale. The next best option is to scale your mesh imports in your mesh’s import settings. With certain optimizations based on the import size, instantiating objects with adjusted scale values may reduce performance.

Component

A GmeObject is an object that contains components in the Unity editor. Components define the behavior of game objects. To view the components of a game object, select the game object in the Scene window or Hierarchy window, and then view a list of all components and their settings in the Inspector window. You can interact with components directly in the editor or through scripts.

Writing scripts (or creating scripts) is writing your own added Unity Editor features in code using the Unity Scripting API. When you create a script and attach it to a game object, the script appears in the inspector of the game object just like built-in components. This is because when you save the script to your project, they become components. Technically speaking, any script you make is a component type, so the Unity editor treats your script as a built-in component. Define the script members to expose in the inspector, and then the editor executes any function

Activation state

You can mark a game object as inactive to temporarily remove it from the scene. To do this,

Navigate to the Inspector, uncheck the checkbox next to the game object name (see image below), or use the SetActive method in the script. If you want to check in the script when an object is marked as active or inactive, check the activeSelf property.

When you deactivate a parent GameObject, you deactivate all its child GameObjects as well. Deactivate the activeSelf setting that overrides all child GameObjects, so Unity deactivates the entire level down from the parent. This does not change the value of the child GameObject’s activeSelf property, so when you reactivate the parent GameObject, they will return to their original state.

Note: This means that you cannot determine if a child game object is active in the scene by reading its activeSelf property, because its parent object may be inactive even if it is set to active.

That is to say, the activeSelf property refers to the property of the GameObject itself, and is not necessarily whether the GameObject is activated in the scene, that is, if the avtiveSelf of the parent object is deactivated, it will not change the activeSelf property of the child. You go to judge that the property of the child is still true, but the self-object will not be displayed and executed.

Tag

A tag is a reference word that you can assign to one or more game objects. For example, you can define a Player Tag for a player-controlled character and an Enemy Tag for a non-player-controlled character. You can define items that players can collect in a scene with collectible tags. Tags can help you identify game objects that are used to write scripts.

They ensure that you do not need to manually add game objects to the exposed properties of the script using drag and drop, thus saving time when you use the same script code on multiple game objects. Tags are useful for Collider to control triggers in scripts.

That is, when multiple different types of GameObjects have some logical similarity, the Tag of these GameObjects can be set to the same, thus simplifying development complexity.

Static objects

If a game object does not move at runtime, it is called a static game object. If a game object moves at runtime, it is called a dynamic game object. Many systems in Unity can pre-calculate information about static game objects in the editor. Because game objects do not move, the results of these calculations are still valid at runtime. This means that Unity can save runtime calculations and potentially improve performance.

A GameObject without a rigid body and without a collider will be regarded as a static object - there is this statement in the impression, to be verified

The Static Editor Flags property lists a number of Unity systems that can include a static GameObject in their precomputation. Use a drop-down list to define which systems should include GameObjects in their precomputation. Setting the Static Editor Flags at runtime has no effect on these systems. You should only include a GameObject in your system’s precomputation because the system needs to know about this GameObject. Including GameObjects in the precomputation of systems that don’t need to know GameObjects can lead to wasted computations, unnecessary Big data files, or accidents

The Static Editor Flags property is located in the inspector of the game object, at the top right. It consists of a checkbox and a drop-down menu that sets the value to Everything or Nothing, and the drop-down menu allows you to choose which values to include. You can also set the Static Editor Flags property in your code using GameObjectUtility.

Prefab

Unity’s Prefab system allows you to create, configure, and store game objects complete with all components, property values, and child game objects as reusable assets. Prefab Asset serves as a template for creating new Prefab instances in your scene.

When you want to reuse a game object in a specific way (such as non-player characters (NPCs), items or scenes from multiple places in a scene, or scenes from multiple scenes in a project), you should convert it to Prefab. This is better than simply copying and pasting game objects, as the Prefab system allows you to automatically keep all copies in sync.

You can nest prefab inside other prefab (Unity - Manual: Nested Prefabs) to create complex object hierarchies that are easy to edit at multiple levels. However, this does not mean that all prefab instances must be the same. If you want some instances of a prefab to be different from others, you can override settings on a single prefab instance. You can also create variations of Prefab, allowing you to combine a set of overrides into a meaningful Prefab variant.

Some common examples of prefab usage include:

  • Environmental assets - such as a certain type of tree used multiple times in a level
  • Non-Player Characters (NPCs) - For example, a certain type of bot may appear multiple times in your game, spanning multiple levels. They may differ in the speed at which they move or the sound they make (use overload)
    Projectiles A pirate cannon, for example, might instantiate a shell prefab each time it is fired.
  • The player’s main character - The player’s prefab may be placed at the starting point of each level (separate scene) of the game.

Create prefabs and their instances

To create a Prefabs asset, drag a GameObject from the Hierarchy window to the Project window. GameObjects and all their components and child GameObjects will become new assets in the Project window. Prefabs assets in the Project window appear as a thumbnail view of GameObjects, or a blue cube Prefab icon, depending on how you set up the Project window.

This process of creating a prefab asset also turns the original game object into a prefab instance. It is now an instance of the newly created prefab asset. The prefab instance is displayed in the hierarchy as blue text, and the prefab root game object is displayed as a blue cube prefab icon

You can create an instance of a prefab asset in the editor by dragging it from the project view to the hierarchy or scene view

You can also use scripts to create Prefabs instances at runtime.

You can replace a Prefab by dragging a new GameObject from the Hierarchy window and dropping it on top of an existing Prefab asset in the Project window. If you’re replacing an existing Prefab, Unity tries to save references to the Prefab itself and individual parts of the Prefab (such as child game objects and components). To do this, it matches the name of the GameObject between the new Prefab and the existing Prefab you’re replacing (this replacement is based on the name only principle, so be aware).

Two modes of editing Prefab

Unity - Manual: Editing a Prefab in Prefab Mode

Instances can override default properties of Prefab

Unity - Manual: Instance overrides

In the Inspector window, the name label covered by the instance is displayed in bold with a blue line in the left margin. When you add a new component to a Prefab instance, the blue line in the margin spans the entire component.

The Overlay drop-down window displays all overlays on a Prefab instance. It also allows you to apply an overlay from an instance to a Prefab asset, or restore an overlay on an instance to a value on a Prefab asset. The Overlay drop-down button appears only on the root Prefab instance, not on Prefab inside other Prefabs. The Overlay drop-down window allows you to apply or restore Prefab overlay individually, or apply or restore all Prefab overlay at once.

img

Prefabricated variant

Prefab variants are useful when you want to have a predefined set of prefab variants. For example, you may want to have several different types of GermSlimeTarget in your game, all based on the same basic GermSlimeTarget prefab. However, you may want some GermSlimeTargets to carry items, some to move at different speeds, or some to make extra sound effects.

One prefab variant inherits the properties of another prefab, called Base. Overrides to the prefab variant will take precedence over the value of the base prefab. A prefab variant can have any other prefab as its base, including model prefab or other prefab variants.

Unity - Manual: Prefab Variants

Hierarchical overrides for overrides and variants

覆盖多个级别 - Unity 手册

Unzip Prefab

解压缩预制件实例 - Unity 手册

It is to turn a prefab instance into a regular GameObject, detached from the prefab.

Layer

Layers in Unity define which game objects can interact with different features. They are often used by cameras to render part of the scene and by lights to illuminate part of the scene. But they can also be used to selectively ignore colliders or create collisions by casting light.

With the camera’s culling mask, you can selectively render objects located in a specific layer. To do this, select the camera that requires partial rendering of the object.

By using layers, you can cast rays and ignore colliders in a specific layer. For example, you might want to cast rays only on the player layer and ignore all other colliders.

The Physics. Raycast function takes a bitmask, in which each bit determines whether the layer will be ignored. If all bits in layerMask are enabled, all colliders will be able to collide. If layerMask = 0, no collisions will occur for the projected rays.

Unity - Manual: Layers

Unity - Manual: Layer-based collision detection

Constraints

Unity - Manual: Constraints

Constraint components associate the position, rotation, or scaling of a game object with another game object. Constrained game objects move, rotate, or scale like the associated game object.

Unity supports the following types of constraint components:

  • AimRotates the constrained game object towards the associated game object.

  • Look AtRotate the constrained game object to the associated game object (simplified Aim Constraint).

  • ParentMake the constrained game object move and rotate with the associated game object.

  • PositionMove the constrained game object like the associated game object.

  • RotationRotate the constrained game object like the associated game object.

  • ScaleScale constrained game objects like associated game objects.

Connect to game objects

Use the Sources list in the constraint component to specify the game object to associate with.

For example, to have the crosshairs follow the player’s spaceship in a 2D shooter, add a Position Constraint component to the crosshairs. To associate the crosshairs to the spaceship, navigate to the Position Constraint component and add the spaceship gameobject to the Sources list. When the player moves the spaceship, the crosshairs move with it.

A constraint can be associated with multiple source game objects. In this case, the constraint uses the average position, rotation, or scaling of its source game object. For example, to point a light source at a set of game objects, add the Aim Constraint component to the light source game object. Then, add the game object to be illuminated to the Sources list. Aim Constraint directs a light source to the average position of its light source.

Unity evaluates source game objects in the order in which they appear in the Sources list. This order has no effect on the Position Constraints and Scale Constraints components. However, the order has an effect on the Parent Constraints, Rotation Constraints and Aim Constraints components. To get the results you want, reorder the Sources list by dragging and dropping items.

You can constrain a range of game objects. For example, suppose you want ducklings to line up to follow their mother. Add the Position Constraint component to the game object Duckling1. In the Sources list, associate it with MotherDuck. Then add Position Constraint to the Duckling2_, which in turn associates it with Duckling1. As MotherDuck_ game object moves through the scene, Duckling1 follow MotherDuck_ and _Duckling2 follow Duckling1.

Set constraint properties

Use Inspector 窗口Common properties in constraints can be changed.

img

Position Constraint 的 Weight 和 Constraint Settings

The effect of a constraint can be changed using the Weight property. A weight of 1 causes the constraint to update the game object at the same rate as its source game object. A weight of 0 completely removes the effect of the constraint. Each source game object also has a separate weight.

In Constraint Settings, use the At Rest property to specify the X, Y, and Z values to use when Weight is 0 or when the corresponding property in Freeze Axes is unchecked.

Use the Offset property in Constraint Settings to specify the X, Y, and Z values to use when constraining game objects.

Use the Freeze Axes setting to toggle which axes the constraint can actually modify.

Activation and locking constraints

Constraints can be used in two ways: activation and locking.

Position, rotation, or scaling of constrained game objects can be evaluated by activating constraints. Unity does not evaluate inactive constraints.

Game objects can be moved, rotated, or scaled by locking constraints. Locked constraints control the game object’s变换组件Unable to manually move, rotate, or scale game objects using locked constraints. Also unable to edit Constraint Settings.

To manually edit the position, rotation, or scaling of a game object, unlock its constraint. If the constraint is active and unlocked, the constraint updates when you move, rotate, or scale the constrained game object or its source game object.

When a constraint component is added to a GameObject, the constraint is inactive and unlocked by default. Therefore, it is possible to fine-tune the position, rotation, and scaling of the constrained GameObject and the source GameObject before activating and locking the constraint.

For convenience, Activate and Zero buttons can update Constraint Settings:

  • ** Activate__: saves the current offset relative to the source game object, then activates and locks the constrained game object **. __

  • Zero: Reset position, rotate or scale to match the source game object, then activate and lock the constrained game object.

Animation and combinatorial constraints

Use animation clips to modify the source game object to which the constrained game object is associated. When the animation modifies the source game object, the constraint modifies the constrained game object.

You can also animate properties in constraint components. For example, use a Parent Constraint to move a character’s sword from their hand to their back. First, add a Parent Constraint to the Sword GameObject. In the Sources list, associate the constraint to the character’s hand and the character’s spine. To animate the sword, add a keyframe for the weight of each source. To animate the movement of the sword from the back to the hand, add a keyframe to change the weight of the hand from 0 to 1, and a keyframe to change the weight of the spine from 1 to 0.

Multiple types of constraint components can be added to the same game object. When updating a game object, Unity will follow the constraint components in Inspector 窗口Evaluate these components in the order in which they appear. A game object can only contain one constraint component of the same type. For example, multiple Position Constraints cannot be added.

Rotation and Direction in Unity

https://docs.unity3d.com/cn/current/Manual/QuaternionAndEulerRotationsInUnity.html

Light source

https://docs.unity3d.com/cn/current/Manual/Lights.html

Camera

https://docs.unity3d.com/cn/current/Manual/Cameras.html

Build release

https://docs.unity3d.com/2020.3/Documentation/Manual/PublishingBuilds.html

Features of the editor

Mode switching

https://docs.unity3d.com/cn/current/Manual/2DAnd3DModeSettings.html

Default value

https://docs.unity3d.com/cn/current/Manual/Preferences.html

There are cache servers and performance analyzers that need to be paid attention to

Shortcut management

https://docs.unity3d.com/cn/current/Manual/ShortcutsManager.html

Build settings

https://docs.unity3d.com/cn/current/Manual/BuildSettings.html

Project settings

https://docs.unity3d.com/cn/current/Manual/comp-ManagerGroup.html

The following list shows the default settings categories available in the Project Settings window.

Depending on the packages installed, the Project Settings window may also display additional categories and settings.

Visual

https://docs.unity3d.com/cn/current/Manual/VisualStudioIntegration.html

RenderDoc集成

https://docs.unity3d.com/cn/current/Manual/RenderDocIntegration.html

Xcode frame debugger

https://docs.unity3d.com/cn/current/Manual/XcodeFrameDebuggerIntegration.html

Version control

https://docs.unity3d.com/cn/current/Manual/Versioncontrolintegration.html

https://docs.unity3d.com/cn/current/Manual/TextSceneFormat.html

Safe mode

https://docs.unity3d.com/cn/current/Manual/SafeMode.html

Performance analyzer

https://docs.unity3d.com/cn/current/Manual/analysis.html