这是用户在 2025-7-9 15:44 为 https://dev.to/codemaker2015/unity3d-fundamentals-3g9 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

DEV Community

Cover image for Unity3D Fundamentals
Vishnu Sivan
Vishnu Sivan  维什努·西万

Posted on   发布于

7 2

Unity3D Fundamentals   Unity3D 基础教程

Unity is a cross-platform game engine designed for the development of 2D and 3D games. It supports more than 20 platforms for deploying such as Android, PC, and iOS systems. Unity is also capable of creating AR VR content and is considered as one of the best platforms for building metaverse content.
Unity 是一款专为开发 2D 和 3D 游戏而设计的跨平台游戏引擎。它支持包括 Android、PC 和 iOS 系统在内的 20 多个部署平台。Unity 还能够创建增强现实(AR)和虚拟现实(VR)内容,被认为是构建元宇宙内容的最佳平台之一。

In this article, we will learn the basic building block of Unity3D such as Assets, GameObjects, Prefabs, Lighting, Physics, and Animations.
在本文中,我们将学习 Unity3D 的基本构成要素,包括资源(Assets)、游戏对象(GameObjects)、预制件(Prefabs)、光照(Lighting)、物理系统(Physics)和动画(Animations)。

Assets   资产

An asset is the representation of an item used in the project. Assets are divided into two - internal and external. The assets created inside the Unity IDE are called internal assets. For example, Animator Controller, an Audio Mixer, Render Texture, etc. External assets are assets which are imported to Unity such as a 3D model, an audio file, or an image.
资产是项目中使用的物品的表现形式。资产分为两类——内部资产和外部资产。在 Unity 集成开发环境中创建的资产称为内部资产,例如动画控制器、音频混音器、渲染纹理等。外部资产则是导入到 Unity 中的资源,如 3D 模型、音频文件或图像。

assets
Image credits by Unity 3D documentation
图片来源于 Unity 3D 官方文档

A few important internal assets are listed below,
以下列出了一些重要的内部资源:

  • Scenes − A container for holding the game objects.
    场景 - 用于存放游戏对象的容器。
  • Animations − Holds gameObject animation data.
    动画(Animations)− 存储游戏对象的动画数据。
  • Materials − Defines the appearance of an object.
    材质(Materials)− 定义物体的外观表现。
  • Scripts − Business logic applied on various gameObjects.
    脚本(Scripts)− 应用于各类游戏对象的业务逻辑。
  • Prefabs − Blueprint of a gameObject and can be generated at runtime.
    预制体(Prefabs)− 游戏对象的蓝图,可在运行时生成。

To create an internal asset, right-click in the Assets folder and go to Create then select the required asset.
要创建内部资源,请在 Assets 文件夹中右键点击,然后选择创建并选取所需资源。

asset

GameObjects   游戏对象

GameObjects are the building blocks of Unity. It acts as a container that holds the components of an object such as lighting, characters, and UI. We can create different game objects by the addition or removal of some components from the game object.
GameObject 是 Unity 的基础构建单元。它作为容器承载着对象的各类组件,例如光照、角色和用户界面。我们可以通过添加或移除游戏对象中的组件来创建不同的游戏对象。

game object
In figure (fig1), You can see the game objects - Main camera, directional light, Cube, Sphere and plane.
在图(fig1)中,你可以看到游戏对象——主摄像机(Main camera)、定向光(directional light)、立方体(Cube)、球体(Sphere)和平面(plane)。

Scene Status properties
场景状态属性

Users can modify the status of a game object via script or by using the inspector. A game object has three statuses - active (default), inactive, and static.
用户可通过脚本或检视器修改游戏对象状态。游戏对象共有三种状态:激活状态(默认)、非激活状态和静态状态。

Active and Static Status
激活与静态状态

By default, the game object is set to active state. Users can set the status of a game object as active, inactive, or static. You can make the object inactive by deselecting the checkbox in the inspector which will make the object invisible. It will not receive any events such as Update or FixedUpdate. You can control the status of gameobject using the script GameObject.SetActive. You can make gameObjects static by checking the static checkbox in the inspector thereby restricting the transformations.
默认情况下,游戏对象处于激活状态。用户可将游戏对象状态设置为激活(active)、非激活(inactive)或静态(static)。通过在检视器中取消勾选复选框可使对象转为非激活状态,此时对象将不可见且不会接收 Update 或 FixedUpdate 等事件。可通过脚本 GameObject.SetActive 控制游戏对象状态。若勾选检视器中的 static 复选框,则游戏对象将转为静态状态并禁止变换操作。

status

Tags and Layers
标签与层级

Tags are useful for identifying the type of a GameObject. The layers provide an option to include or exclude groups of GameObjects from certain actions such as rendering or physics collisions. You can modify tag and layer values using the GameObject.tag and GameObject.layer properties.
标签(Tags)对于识别游戏对象类型非常有用。层级(Layers)提供了将游戏对象分组包含或排除在特定操作(如渲染或物理碰撞)之外的选项。你可以使用`tag`和`layer`属性来修改标签和层级值。

tags and layers

Creating and Destroying GameObjects
创建与销毁游戏对象

You can create and destroy GameObjects dynamically. We can create GameObjects in Unity by calling the Instantiate() method at run time. This process will create a duplicate element of the object provided it is passed in the argument. We can remove the contents from the scene by calling the Destroy() method.
你可以动态创建和销毁游戏对象。在 Unity 中,我们可以通过运行时调用`Instantiate`方法来创建游戏对象。该过程会生成传入参数对象的副本元素。我们可以通过调用`Destroy`方法从场景中移除内容。

Object Instantiation   对象实例化

public GameObject cube;  
void Start() {  
    for (int i = 0; i < 5; i++) {  
        Instantiate(cube);  
    }  
}
Object Destruction
void OnCollisionEnter(Collision otherObj) {  
    if (otherObj.gameObject.tag == "Cube") {  
        Destroy(otherObj,.5f);  
    }  
}
Enter fullscreen mode Exit fullscreen mode

This code snippet will destroy otherObj if it collides with the gameobject.
如果发生碰撞,此代码片段将销毁 otherObj 游戏对象。

Finding GameObjects by Name or Tag
通过名称或标签查找 GameObject

We can locate an individual gameobject by its name using the GameObject.Find() function whereas a collection of objects can be located by their tag using the GameObject.FindWithTag() and GameObject.FindGameObjectsWithTag() methods.
我们可以通过 GameObject.Find() 函数按名称定位单个游戏对象,而通过 GameObject.FindWithTag()GameObject.FindGameObjectsWithTag() 方法则可以根据标签定位一组对象。

GameObject player;
GameObject bat;
GameObject[] balls;
void Start()
{
    player = GameObject.Find("Player1");
    bat = GameObject.FindWithTag("Bat");
    balls = GameObject.FindGameObjectsWithTag("Ball");
}
Enter fullscreen mode Exit fullscreen mode

Finding child GameObjects
查找子游戏对象

The child GameObjects can be located using the parent object's transform component reference and the GetChild() method.
子游戏对象可以通过父对象的 transform 组件引用和 GetChild() 方法进行定位。

void Start()
{
    for(int i=0;i<gameobject.transform.childCount;i++)
        balls[i] = gameobject.transform.GetChild(i).gameObject;
}
Enter fullscreen mode Exit fullscreen mode

Linking to GameObjects with variables
通过变量链接到游戏对象

The simplest way to find a gameObject is to add a public variable to the script which refers to the gameObject.
查找游戏对象的最简单方法是向脚本添加一个引用该游戏对象的公共变量。

public class Demo : MonoBehaviour
{
    public GameObject bat;
    // Other variables and functions...
}
Enter fullscreen mode Exit fullscreen mode

The public variables will be visible in the Inspector. You can assign objects to the variables by dragging the object from the scene or from the Hierarchy panel.
公共变量会在 Inspector 面板中显示。你可以通过从场景或 Hierarchy 面板拖拽对象来为这些变量赋值。

Linking to GameObjects with variables

Unity Components   Unity 组件

Components are functional pieces of a GameObject. You can assign a component to the gameobject to add a functionality. Transform, Mesh Renderer, Mesh Filter, Box Collider are some of the components of GameObject.
组件是 GameObject 的功能模块。你可以为游戏对象分配组件来添加功能。Transform(变换)、Mesh Renderer(网格渲染器)、Mesh Filter(网格过滤器)和 Box Collider(盒状碰撞器)都是 GameObject 的组件。

As mentioned earlier, a GameObject is a container that holds different components. All GameObjects by default have a Transform component to define basic transformations such as translation, rotation and scale.
如前所述,GameObject 是一个承载不同组件的容器。默认情况下,所有 GameObject 都拥有一个 Transform 组件,用于定义基本的变换操作,包括平移、旋转和缩放。

Unity Components

Component Manipulations
组件操作

Accessing components   访问组件

GetComponent() method is used to get a reference of the required component instance. Once you have a reference to a component instance, you can change the values of its properties or the references which are similar to changing values in the inspector panel.
GetComponent() 方法用于获取所需组件实例的引用。一旦获得组件实例的引用,即可修改其属性值或引用,这与在检视面板中修改数值类似。

void Start ()
{
    Rigidbody rb = GetComponent<Rigidbody>();
    rb.mass = 1f;
    rb.AddForce(Vector3.down * 5f);
}
Enter fullscreen mode Exit fullscreen mode

In this example, the script receives a reference of a Rigidbody component, the mass is set to 1, and AddForce is set to down direction with a multiplier of 5. 
在此示例中,脚本接收一个 Rigidbody 组件的引用, mass 设置为 1, AddForce 设置为向下方向并带有 5 倍的乘数。

Add or remove components
添加或移除组件

You can add or remove components at runtime using the AddComponent and Destroy methods. The method can be used to add / remove gameobjects dynamically to the scene. However, you can enable or disable some components via script without destroying them.
您可以使用 AddComponentDestroy 方法在运行时添加或移除组件。该方法可用于动态地向场景中添加/移除游戏对象。不过,您也可以通过脚本启用或禁用某些组件而无需销毁它们。

You can add a component to the object using the AddComponent<Type> and by specifying the type of component within angle brackets as shown. To remove a component, you can use Object.Destroy method.
您可以使用 AddComponent<Type> 并如所示在尖括号内指定组件类型来为对象添加组件。要移除组件,可以使用 Object.Destroy 方法。

//Adding a component to the current gameObject
void Start ()
{
    gameObject.AddComponent<Rigidbody>();
}
//Removing a component from the current gameObject
void Start ()
{
    Rigidbody rb = GetComponent<Rigidbody>();
    Destroy(rb);    
}
Enter fullscreen mode Exit fullscreen mode

Prefabs   预制体(Prefabs)

Prefabs are reuse gameobjects which allows the user to store a GameObject with its complete components and properties. These assets can then be shared between scenes. A major benefit of prefab is that the changes made or applied to the original Prefab will be propagated to all the other instances. This is useful when fixing object errors, making material changes, all in a single instance.
预制体是可重复使用的游戏对象,允许用户存储带有完整组件和属性的游戏对象。这些资源可以在不同场景之间共享。预制体的一个主要优势是对原始预制体所做的更改会传播到所有其他实例中。这在修复对象错误、进行材质修改时尤为有用,只需修改单个实例即可。

Prefabs are created automatically when an object is dragged from the Hierarchy into the Project window. Prefabs are represented with blue text and a blue cube and an extension of *.prefab.
当从层级视图(Hierarchy)中将对象拖拽到项目窗口(Project)时,预制体会自动创建。预制体以蓝色文字、蓝色立方体图标和*.prefab 扩展名表示。

Prefab

Rendering   渲染

Camera   相机

Camera is a component that captures the view from the scene. It is mandatory to have at least one camera in the scene to visualize the game objects. By default, there is a Main Camera component in the scene when a new scene is created.
相机是用于捕捉场景视角的组件。场景中必须至少有一个相机才能可视化游戏对象。默认情况下,创建新场景时会自带一个主相机组件。

Camera

Materials, Shaders and Textures
材质、着色器与纹理

Materials, Shaders and Textures are the core components to render game objects in a scene.
材质、着色器和纹理是渲染场景中游戏对象的核心组件。

Materials   材质

Materials define how the surface is to be rendered which includes texture, transparency, color, reflectiveness, etc.
材质定义了表面的渲染方式,包括纹理、透明度、颜色、反射率等属性。

Material
Fig 1. Material creation 2. Material location in Assets 3. Material specifications in Inspector
图 1. 材质创建 2. Assets 中的材质位置 3. Inspector 面板中的材质参数

Materials act as a container for shaders and textures which can be applied to the model. Customization of Materials depends on the shader that is used in the material.
材质作为着色器(shaders)和纹理(textures)的容器,可应用于模型。材质的自定义选项取决于该材质所使用的着色器类型。

Shaders   着色器

Shaders are small scripts that render graphics data by integrating meshes, textures, etc. as the input and generating an image as the output.
着色器是通过整合网格、纹理等作为输入并生成图像作为输出的小型脚本,用于渲染图形数据。

Shaders

Textures   纹理

Textures are bitmap images which can be used with material shaders to calculate the surface color of an object. In addition to the base color (albedo), textures can represent other aspects of the surface such as reflectivity and roughness.
纹理是位图图像,可与材质着色器配合使用来计算物体表面的颜色。除了基础颜色(反照率)外,纹理还能表现表面的其他特性,如反射率和粗糙度。

Textures

Lighting   光照

Lighting is useful to create realistic shadows and properly lit environment props. However, we also need to consider the performance of these lighting calculations.
光照对于创建逼真的阴影和恰当照明的环境道具非常有用。然而,我们也需要考虑这些光照计算的性能表现。

Unity provides three modes for lighting based on lighting calculations. They are realtime, mixed, or baked lighting.
Unity 提供了三种基于光照计算的照明模式:实时光照、混合光照和烘焙光照。

Lighting modes

  • Realtime lighting is the best lighting mode where we can create dynamic shadows. However, they are the most expensive ones to use. It is recommended to keep the real-time lighting to a minimum and add only when necessary.
    实时光照是最佳的光照模式,可以创建动态阴影。但它们也是性能消耗最大的方式。建议尽量减少实时光照的使用,只在必要时添加。
  • Baked lighting allows us to take a "snapshot" of our lighting in the game. It enables the calculation of shadows and highlights from the lights in the scene at runtime.
    烘焙光照允许我们对游戏中的光照进行"快照"。它能够在运行时预先计算场景中光源产生的阴影和高光效果。
  • Mixed lighting is a combination of real-time and baked lighting features.
    混合光照是实时光照与烘焙光照功能的结合体。

Along with the lighting settings, you may also want to play around with some of the lighting settings. Go to Window > Rendering > Lighting Settings.
除了光照设置外,您可能还想尝试调整一些光照参数。前往 Window > Rendering > Lighting Settings

Lighting

  • Enable Real-time Lighting if you are not using any real-time lighting within your scene.
    如果场景中没有使用任何实时光照,请启用"实时光照"选项。
  • Select a lighting mode from - Shadow mask, Baked Indirect, and Subtractive.
    从阴影遮罩、烘焙间接光和减法模式中选择一种光照模式。
  • Shadow mask provides the best lighting features but is expensive.
    阴影遮罩提供最佳的光照效果,但成本较高。
  • Baked Indirect is useful for indoor scenes.
    烘焙间接光适用于室内场景。
  • Subtractive is the most performant and is used for WebGL or mobile platforms.
    减法模式性能最优,常用于 WebGL 或移动平台。

Lights   灯光

Directional Lights   定向光源

Directional Lights can be thought of as a distant light source which exists infinitely far away like the sun.
可以将定向光源想象成存在于无限远处的光源,就像太阳一样。

Directional Lights
Rays from Directional Lights are always parallel to one another, hence shadows cast look the same. We can place it anywhere in the scene without changing the effect of the light as it does not have a source position. These are useful for outdoor scenes.
来自定向光源的光线始终彼此平行,因此投射的阴影看起来相同。我们可以将其放置在场景中的任何位置而不会改变光照效果,因为它没有具体的光源位置。这种光源非常适合户外场景。

Point Lights   点光源

A Point Light is a point from which light is emitted in all directions. The intensity of light diminishes from its full intensity at the center to zero at the light range. These are useful for creating effects like electric bulbs, lamps, and all.
点光源是从某一点向所有方向发射光线的光源。光线强度从中心处的最大值逐渐衰减,到光源作用范围边界时降为零。这类光源非常适合用来模拟电灯泡、灯具等发光效果。

Point Lights

Spotlights   聚光灯

Spotlights emit light in the forward (+Z) direction as a conical structure. The width of this cone is defined by the light's Spot Angle parameter. The light intensity diminishes towards the length of the cone and is minimum at its base.
聚光灯以圆锥体结构沿正 Z 轴方向发射光线。圆锥的宽度由聚光灯的 Spot Angle 参数定义。光线强度随着圆锥长度方向逐渐衰减,在圆锥底部达到最小值。

Spotlights
Spotlights have many useful applications for scene lighting. They can be used to create street lights, wall downlights, or flashlights. These are extremely useful for creating a focus on a character as their area of influence can be precisely controlled.
聚光灯在场景照明中有许多实用场景。可用于创建路灯、墙面射灯或手电筒效果。由于可以精确控制其影响范围,这类光源特别适合用于突出角色焦点。

Physics   物理

Physics enables objects to be controlled by the forces which exist in the real world, such as gravity, velocity, and acceleration. Unity Physics is a combination of deterministic rigid body dynamics systems and spatial query systems. It is written from scratch using the Unity data-oriented tech stack.
物理系统使得对象能够受到现实世界中存在的各种力的控制,比如重力、速度和加速度。Unity 物理引擎是由确定性刚体动力学系统和空间查询系统组合而成,完全基于 Unity 数据导向技术栈从头编写。

Colliders   碰撞体

Colliders are the components used to detect collisions when GameObjects strike or collider each other. We must add Rigidbody component to the GameObject where we attached the collider component.
碰撞体是用于检测游戏对象(GameObject)之间相互碰撞的组件。我们必须为附加了碰撞体组件的游戏对象添加刚体(Rigidbody)组件。

Collider types: Box Collider, Capsule Collider, Mesh Collider, Sphere Collider, Terrain Collider, and Wheel Collider.
碰撞体类型:盒型碰撞体(Box Collider)、胶囊碰撞体(Capsule Collider)、网格碰撞体(Mesh Collider)、球形碰撞体(Sphere Collider)、地形碰撞体(Terrain Collider)和车轮碰撞体(Wheel Collider)。

Colliders

To add physics events to a GameObject, select the Add Component button in the Inspector window, select Physics, and specify the type of Collider.
要为 GameObject 添加物理事件,在 Inspector 窗口中选择 Add Component 按钮,选择 Physics 类别并指定所需的 Collider 类型。

Triggers   触发器

Triggers are enabled when Is Trigger checkbox is selected. This function disables the physics events thereby enabling objects to pass through the game objects. The physics events onTriggerEnter and onTriggerExit are called when the gameObject enters or exits the trigger.
当勾选 Is Trigger 复选框时,触发器功能将被启用。该功能会禁用物理事件,从而允许物体穿透游戏对象。当游戏对象进入或离开触发器时,会调用 onTriggerEnteronTriggerExit 物理事件。

Triggers

Rigidbody   刚体(Rigidbody)

We can control a character in two ways using the physics engine.
我们可以通过两种方式利用物理引擎来控制角色。

In the Rigidbody approach, the character behaves like a regular physics object and is controlled indirectly by applying forces or by changing the velocity.
在 Rigidbody 方法中,角色的行为类似于常规物理对象,通过施加力或改变速度来间接控制。

In the Kinematic approach, the character is controlled directly and only queries the physics engine to perform custom collision detection.
在 Kinematic 方法中,角色被直接控制,仅通过查询物理引擎来执行自定义碰撞检测。

Rigidbody

Adding the Rigidbody component is enough to turn the gameobject into a physics object. As a best practice, attach any one of the colliders with the gameobject.
为游戏对象添加 Rigidbody 组件即可使其成为物理对象。最佳实践是同时为游戏对象附加任意一种碰撞体组件。

Scripting   脚本编写

These are the physics events in Unity for detecting collisions.
这些是 Unity 中用于检测碰撞的物理事件。

OnCollisionEnter(Collision) is called when a collision is registered.
OnCollisionEnter(Collision) 在碰撞被注册时调用。

void OnCollisionEnter(Collision collision) { 
 if(collision.gameObject.CompareTag("Ball") { 
  //Hit the ball
 } 
}
Enter fullscreen mode Exit fullscreen mode
  • OnCollisionStay(Collision) is called during a collision
    OnCollisionStay(Collision) 在碰撞过程中调用
  • OnCollisionExit(Collision) is called when a collision has stopped
    当碰撞停止时调用 OnCollisionExit(Collision)
  • useGravity is used to enable or disable gravity.
    useGravity 用于启用或禁用重力
  • AddForce() is used to add a force in a particular direction. Eg: rigidBody.AddForce(Vector3.up)
    AddForce() 用于在特定方向上施加力。例如: rigidBody.AddForce(Vector3.up)

Animation   动画

It is easy to create an animation in Unity. Unity has made the task simple with the help of Animator controls and Animation Graph. Unity calls the animator controllers to handle which animations to play and when to play them. The animation component is used to playback animations.
在 Unity 中创建动画非常容易。Unity 通过 Animator 控制组件和动画图表简化了这一过程。Unity 调用动画控制器来决定播放哪些动画以及何时播放它们。动画组件则用于播放动画。

It is quite simple to interact with the animation using a script. First, you have to refer the animation clips to the animation component. Then get the Animator component reference in the script via GetComponent method or by making that variable public.
通过脚本与动画交互相当简单。首先需要将动画片段关联到动画组件,然后通过 GetComponent 方法获取 Animator 组件引用,或是将该变量设为 public 公开访问。

Finally, set enabled attribute value to true for enabling the animation and false for disabling it.
最后,将 enabled 属性值设为 true 以启用动画,设为 false 则禁用动画。

For creating animation on a gameObject,
要为游戏对象创建动画,

  • First, select the object in the hierarchy and press ctrl + 6 or Window → Animation → Animation
    首先在层级视图中选中对象,然后按下 ctrl + 6Window → Animation → Animation

Animation

  • Click on Create. then a window will pop up asking you to specify the filename. Name it as per your likes. Here it is rotateAnim.
    点击创建。随后会弹出一个窗口要求指定文件名。按您的喜好命名即可,此处命名为 rotateAnim
  • In the animation window, click the record button and then Add Property button. Choose Transform → Rotation.
    在动画窗口中,点击录制按钮,然后点击添加属性按钮。选择 Transform → Rotation。

Animation
Animation

  • Change the keyframe to 60 and change the X-axis rotation value from 0 to 60. Change the X-axis rotation of the cube to 360 degrees.
    将关键帧设为 60,并将 X 轴旋转值从 0 更改为 60。将立方体的 X 轴旋转角度更改为 360 度。

    Animation

  • Play the game. Your cube will rotate on x-axis every 1 second.
    运行游戏。你的立方体会每隔 1 秒绕 x 轴旋转一次。

    Animation demo

Thanks for reading this article.
感谢阅读本文。

Thanks Gowri M Bhatt for reviewing the content.
感谢 Gowri M Bhatt 审阅内容。

To get the article in pdf format: unity3d-fundamentals.pdf
获取本文 PDF 版本: unity3d-fundamentals.pdf

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!
如果喜欢本文,请点击爱心按钮 ♥ 并分享帮助更多人发现它!

If you are interested in further exploring, here are some resources I found helpful along the way:
如果你有兴趣进一步探索,以下是我在学习过程中发现的一些有用资源:

Unity 3D C# scripting cheatsheet for beginners
Unity 3D C#脚本初学者速查表

Originally posted on Medium -
最初发表于 Medium

Unity3D Fundamentals  Unity3D 基础教程

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

Top comments (0)
置顶评论 (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post