在 Visual Studio for Mac 中开始使用 Unity 生成游戏Getting started building games with Unity in Visual Studio for Mac

Unity 是一款可让你在 C# 中开发游戏的游戏引擎。Unity is a game engine that enables you to develop games in C#. 本演练演示如何使用 Visual Studio for Mac 和 Visual Studio for Mac Tools for Unity 扩展及 Unity 环境开始开发和调试 Unity 游戏。This walkthrough shows how to get started developing and debugging Unity games using Visual Studio for Mac and the Visual Studio for Mac Tools for Unity extension alongside the Unity environment.

Visual Studio for Mac Tools for Unity 是免费扩展,随 Visual Studio for Mac 一起安装。Visual Studio for Mac Tools for Unity is a free extension, installed with Visual Studio for Mac. 它使 Unity 开发者能够利用 Visual Studio for Mac 的高效功能,包括出色的 IntelliSense 支持、调试功能等。It enables Unity developers to take advantage of the productivity features of Visual Studio for Mac, including excellent IntelliSense support, debugging features, and more.

目标Objectives

  • 了解如何使用 Visual Studio for Mac 进行 Unity 开发Learn about Unity development with Visual Studio for Mac

先决条件Prerequisites

目标受众Intended Audience

本实验室适用于熟悉 C# 但不具有丰富经验的开发者。This lab is intended for developers who are familiar with C#, although deep experience is not required.

任务 1:创建基本 Unity 项目Task 1: Creating a basic Unity project

  1. 启动 Unity 。Launch Unity. 如果要求,请登录。Sign in if requested.

  2. 单击“新建” 。Click New.

    Unity 中的“新建”按钮

  3. 将“项目名称”设置为 UnityLab,然后选择 3D 。Set the Project name to "UnityLab" and select 3D. 单击“创建项目” 。Click Create project.

    创建新的项目屏幕

  4. 你现在看到的是默认 Unity 界面。You're now looking at the default Unity interface. 界面左侧为游戏对象的场景层次结构,中间显示空白场景的 3D 视图,底部为项目文件窗格,右侧为检查器和服务。It has the scene hierarchy with game objects on the left, a 3D view of the blank scene shown in the middle, a project files pane on the bottom, and inspector and services on the right. 当然,除此之外还有很多部分,但这些是更重要的组成部分。Of course, there's a lot more to it than that, but those are few of the more important components.

    空白 Unity 界面

  5. 对于刚接触 Unity 的开发者,在应用中运行的所有内容都将存在于“场景”的上下文中 。For developers new to Unity, everything that runs in your app will exist within the context of a scene. 场景文件是一个文件,其中包含各种关于项目中用于当前场景的资源的元数据及其属性。A scene file is a single file that contains all sorts of metadata about the resources used in the project for the current scene and its properties. 当你针对某个平台打包应用时,由此产生的应用最终将成为一个或多个场景的集合,包括你添加的所有依赖于平台的代码。When you package your app for a platform, the resulting app will end up being a collection of one or more scenes, plus any platform-dependent code you add. 在一个项目中你可以根据需要拥有足够多场景。You can have as many scenes as desired in a project.

  6. 新场景中只有照相机和定向光。The new scene just has a camera and a directional light in it. 场景需要“照相机”才能看到任何内容,需要“音频侦听器”才能听到任何声音 。A scene requires a camera for anything to be visible and an Audio Listener for anything to be audible. 这些组件附加到 GameObject 。These components are attached to a GameObject.

  7. 从“层次结构”窗格中选择“主照相机”对象 。Select the Main Camera object from the Hierarchy pane.

    “层次结构”窗格中突出显示的主照相机对象

  8. 从窗口右侧选择“检查器”窗格,可查看其属性 。Select the Inspector pane from the right side of the window to review its properties. 照相机属性包括转换信息、背景、投影类型、视野等。Camera properties include transform information, background, projection type, field of view, and so on. 还默认添加音频侦听器组件,它实际上从连接到照相机的虚拟麦克风中呈现场景音频。An Audio Listener component was also added by default, which essentially renders scene audio from a virtual microphone attached to the camera.

    “检查器”窗格

  9. 选择“定向光”对象 。Select the Directional Light object. 这将为场景提供光,便于着色器等组件了解如何呈现对象。This provides light to the scene so that components like shaders know how to render objects.

    突出显示定向光对象

  10. 使用“检查器”可以看到其中包含常见的光照属性,包括类型、颜色、强度、阴影类型等 。Use the Inspector to see that it includes common lighting properties including type, color, intensity, shadow type, and so on.

    在“检查器”窗格中查看属性

  11. 请务必指出 Unity 中的该项目与 Visual Studio for Mac 对应项目略有不同。It is important to point out that projects in Unity are a little different from their Visual Studio for Mac counterparts. 在底部的“项目”选项卡中,右键单击“资产”文件夹,然后选择“在查找器中展现” 。In the Project tab on the bottom, right-click the Assets folder and select Reveal in Finder.

    在查找器中展现上下文操作

  12. 如你所见,项目包含“资产”、“库”、“ProjectSettings”和“Temp”文件夹 。Projects contain Assets, Library, ProjectSettings, and Temp folders as you can see. 但是,唯一在界面中显示的文件夹是“资产”文件夹 。However, the only one that shows up in the interface is the Assets folder. “库”文件夹是导入资产的本地缓存;它为资产保留所有元数据 。The Library folder is the local cache for imported assets; it holds all metadata for assets. “ProjectSettings”文件夹存储可配置的设置 。The ProjectSettings folder stores settings you can configure. “Temp”文件夹用于生成过程中来自 Mono 和 Unity 的临时文件 。The Temp folder is used for temporary files from Mono and Unity during the build process. 还有一个解决方案文件可在 Visual Studio for Mac 中打开(此处为 UnityLab.sln) 。There is also a solution file that you can open in Visual Studio for Mac (UnityLab.sln here).

    查找器中的资产

  13. 关闭“查找器”窗口并返回 Unity 。Close the Finder window and return to Unity.

  14. “资产”文件夹中包含你所有的资产 - 艺术品、代码、音频等 。该文件夹此时为空,但你引入项目的每个文件都将进入该文件夹。The Assets folder contains all your assets-art, code, audio, etc. It's empty now, but every single file you bring into your project goes here. 这始终是 Unity 编辑器中的顶层文件夹 。This is always the top-level folder in the Unity Editor. 但始终通过 Unity 界面(或 Visual Studio for Mac)添加和删除文件,从不直接通过文件系统添加和删除文件。But always add and remove files via the Unity interface (or Visual Studio for Mac) and never through the file system directly.

    Unity 中的资产文件夹

  15. GameObject 是 Unity 开发的核心,因为几乎所有内容都派生自该类型,包括模型、光、粒子系统等 。The GameObject is central to development in Unity as almost everything derives from that type, including models, lights, particle systems, and so on. 通过依次选择“GameObject”、“3D 对象”、“多维数据集”菜单,将新的“多维数据集”对象添加到场景中 。Add a new Cube object to the scene via the GameObject > 3D Object > Cube menu.

    场景中的多维数据集对象

  16. 快速浏览新 GameObject 的属性,并查看该属性是否有名称、标记、层和转换 。Take a quick look at the properties of the new GameObject and see that it has a name, tag, layer, and transform. 这些属性是所有 GameObjects 共有的 。These properties are common to all GameObjects. 此外,几个组件已附加到“多维数据集”,用于提供所需的功能,包括网格筛选器、盒状碰撞体和呈现器 。In addition, several components were attached to the Cube to provide needed functionality including mesh filter, box collider, and renderer.

    游戏对象属性

  17. 将“多维数据集”对象(默认名称为“多维数据集”)重命名为“敌人” 。Rename the Cube object, which has the name "Cube" by default, to "Enemy". 确保按 Enter 保存更改 。Make sure to press Enter to save the change. 这将是我们的简单游戏中的敌人多维数据集。This will be the enemy cube in our simple game.

    多维数据集对象重命名属性

  18. 使用以上相同过程,将另一个“多维数据集”对象添加到场景中,并将其命名为“玩家” 。Add another Cube object to the scene using the same process as above, and name this one "Player".

    重命名第二个多维数据集对象

  19. 同样将玩家对象标记为“玩家”(请参阅名称字段下的“标记”下拉控件) 。Tag the player object "Player" as well (see Tag drop-down control just under name field). 我们将在敌人脚本中使用该对象来帮助查找玩家游戏对象。We'll use this in the enemy script to help locate the player game object.

    标记玩家对象

  20. 在“场景”视图中,使用鼠标沿 Z 轴按照远离敌人对象的方向移动玩家对象 。In the Scene view, move the player object away from the enemy object along the Z axis using the mouse. 通过选择多维数据集并将其从红色面板拖向蓝色行,沿 Z 轴移动 。You can move along the Z axis by selecting and dragging the cube by its red panel toward the blue line. 由于多维数据集存在于 3D 空间中,但每次只能在 2D 中拖动,因此拖动中心轴尤其重要。Since the cube lives in 3D space, but can only be dragged in 2D each time, the axis on which you drag is especially important.

    显示多维数据集的场景视图

  21. 沿轴向下和向右移动多维数据集。Move the cube downward and to the right along the axis. 此操作可更新“检查器”中的 Transform.Position 属性 。This updates the Transform.Position property in the Inspector. 请务必拖动到与此处显示的位置类似的位置,以轻松执行实验室中的后续步骤。Be sure to drag to a location similarly to what's shown here to make later steps easier in the lab.

    沿轴移动一个多维数据集

  22. 现可添加一些代码,用来驱动敌人逻辑,使其追逐玩家。Now you can add some code to drive the enemy logic so that it pursues the player. 右键单击“项目”板中的“资产”文件夹,然后依次选择“创建”、“C# 脚本” 。Right-click the Assets folder in the Project pad and select Create > C# Script.

    C# 脚本上下文操作

  23. 将新的 C# 脚本命名为 EnemyAI 。Name the new C# script "EnemyAI".

    C# 脚本

  24. 要将脚本附加到游戏对象,请将新创建的脚本拖到“层次结构”窗格中的“敌人”对象上 。To attach scripts to game objects drag the newly created script onto the Enemy object in the Hierarchy pane. 该对象现将使用此脚本中的行为。Now that object will use behaviors from this script.

    突出显示向游戏对象添加脚本

  25. 依次选择“文件”、“保存场景”,保存当前场景 。Select File > Save Scenes to save the current scene. 将其命名为 MyScene 。Name it "MyScene".

任务 2:与 Visual Studio for Mac Tools for Unity 配合使用Task 2: Working with Visual Studio for Mac Tools for Unity

  1. 编辑 C# 代码的最佳方法是使用 Visual Studio for Mac。The best way to edit C# code is to use Visual Studio for Mac. 可以将 Unity 配置为使用 Visual Studio for Mac 作为默认处理程序。You can configure Unity to use Visual Studio for Mac as its default handler. 依次选择“Unity”、“首选项” 。Select Unity > Preferences.

  2. 选择“外部工具”选项卡 。从“外部脚本编辑器”下拉列表中,选择“浏览”并选择 Applications/Visual Studio.app 。Select the External Tools tab. From the External Script Editor dropdown, select Browse and select Applications/Visual Studio.app. 或者如果已有 Visual Studio 选项,则只需选择该选项即可 。Alternatively, if there's already a Visual Studio option, just select that.

    首选项中的外部工具选项卡

  3. Unity 现配置为使用 Visual Studio for Mac 进行脚本编辑 。Unity is now configured to use Visual Studio for Mac for script editing. 关闭“Unity 首选项”对话框 。Close the Unity Preferences dialog.

    在首选项中已选中 Visual Studio

  4. 双击 EnemyAI.cs,在 Visual Studio for Mac 中打开它 。Double-click EnemyAI.cs to open it in Visual Studio for Mac.

    在 Unity 中已选中“敌人”资产

  5. Visual Studio 解决方案非常简单。The Visual Studio solution is straightforward. 其中包含“资产”文件夹(来自查找器的相同文件夹)和之前创建的 EnemyAI.cs 脚本 。It contains an Assets folder (the same one from Finder) and the EnemyAI.cs script created earlier. 在更复杂的项目中,层次结构可能与你在 Unity 中看到的不同。In more sophisticated projects, the hierarchy will likely look different than what you see in Unity.

    Visual Studio for Mac 中的 Solution Pad

  6. EnemyAI.cs 在编辑器中打开 。EnemyAI.cs is open in the editor. 初始脚本仅包含 Start 和 Update 方法的存根 。The initial script just contains stubs for the Start and Update methods.

  7. 用下面的代码替换最初的敌人代码。Replace the initial enemy code with the code below.

    public class EnemyAI : MonoBehaviour
    {
        public float Speed = 50;
        private Transform _playerTransform;
        private Transform _myTransform;
    
        void Start()
        {
            var player = GameObject.FindGameObjectWithTag("Player");
            if (!player)
            {
                Debug.LogError(
                    "Could not find the main player. Ensure it has the player tag set.");
            }
            else
            {
                _playerTransform = player.transform;
            }
            _myTransform = this.transform;
        }
    
        void Update()
        {
            var moveAmount = Speed * Time.deltaTime;
            _myTransform.position = Vector3.MoveTowards(_myTransform.position,
                _playerTransform.position, moveAmount);
    
            if (_myTransform.position == _playerTransform.position)
            {
                _myTransform.position = Vector3.back * 10;
            }
        }
    }
    
  8. 快速浏览此处定义的简单敌人行为。Take a quick look at the simple enemy behavior that is defined here. 在 Start 方法中,我们可以引用玩家对象(按标记)及其转换 。In the Start method, we get a reference to the player object (by its tag), as well as its transform. 在每帧调用的 Update 方法中,敌人将向玩家对象移动 。In the Update method, which is called every frame, the enemy will move towards the player object. 关键字和名称使用颜色编码,这样可更容易理解 Visual Studio for Mac 中的代码库。The keywords and names use color coding to make it easier to understand the codebase in Visual Studio for Mac.

  9. 将更改保存到 Visual Studio for Mac 中的敌人脚本 。Save the changes to the enemy script in Visual Studio for Mac.

任务 3:调试 Unity 项目Task 3: Debugging the Unity project

  1. 在 Start 方法的第一行代码上设置断点 。Set a breakpoint on the first line of code in the Start method. 可以在目标行上单击编辑器边距,或者将光标放在该行上,然后按 F9 。You can either click in the editor margin at the target line or place cursor on the line and press F9.

    在 Visual Studio for Mac 中设置断点

  2. 单击“开始调试”按钮或按 F5 。Click the Start Debugging button or press F5. 此操作将生成项目并将其附加到 Unity 进行调试。This will build the project and attach it to Unity for debugging.

    Visual Studio for Mac 中的“开始”按钮

  3. 返回 Unity,然后单击“运行”按钮,开始游戏 。Return to Unity and click the Run button to start the game.

    Unity 中的“运行”按钮

  4. 应命中断点,并且现在可以使用 Visual Studio for Mac 调试工具。The breakpoint should be hit and you can now use the Visual Studio for Mac debugging tools.

    Visual Studio for Mac 中的断点命中

  5. 在“局部变量”板中,找到引用 EnemyAI 对象的 this 指针 。From the Locals pad, locate the this pointer, which references an EnemyAI object. 展开引用,可发现你可以浏览“速度”等关联成员 。Expand the reference and see that you can browse the associated members like Speed.

    Visual Studio for Mac 中的局部变量调试板

  6. 采用与添加断点相同的方法从 Start 方法中删除断点,即在边距中单击断点或选择所在行并按 F9 。Remove the breakpoint from the Start method the same way it was added-by either clicking it in the margin or selecting the line and press F9.

    Visual Studio for Mac 中的断点命中

  7. 按 F10 跳过使用标记作为参数查找“玩家”游戏对象的第一行代码 。Press F10 to step over the first line of code that finds the Player game object using a tag as parameter.

  8. 将鼠标光标悬停在代码编辑器窗口中的“玩家”变量上,查看其关联成员 。Hover the mouse cursor over the player variable within the code editor window to view its associated members. 你甚至可以展开层叠,查看子属性。You can even expand the overlay to view child properties.

    Visual Studio for Mac 编辑器中的调试窗口

  9. 按 F5 或按“运行”按钮,继续执行操作 。Press F5 or press the Run button to continue execution. 返回 Unity,查看反复接近玩家多维数据集的敌人多维数据集。Return to Unity to see the enemy cube repeatedly approach the player cube. 如果照相机不可见,则可能需要进行调整。You may need to adjust the camera if it's not visible.

    Unity 中的场景播放

  10. 切换回 Visual Studio for Mac 并在 Update 方法的第一行设置断点 。Switch back to Visual Studio for Mac and set a breakpoint on the first line of the Update method. 应该立即击中该断点。It should be hit immediately.

    在 Visual Studio for Mac 中设置断点

  11. 假设速度太快,而我们想要在不重新启动应用的情况下测试更改的影响。Suppose the speed is too fast and we want to test the impact of the change without restarting the app. 在“自动”或“局部变量”窗口中找到“速度”变量,然后将其更改为“10”并按 Enter 。Locate the Speed variable within the Autos or Locals window and then change it to "10" and press Enter.

    在局部变量窗口中调整变量

  12. 删除断点并按 F5,继续执行操作 。Remove the breakpoint and press F5 to resume execution.

  13. 返回 Unity,查看正在运行的应用程序 。Return to Unity to view the running application. 敌人多维数据集现以原始速度的五分之一移动。The enemy cube is now moving at a fifth of the original speed.

    正在运行应用程序的 Unity 窗口

  14. 再次单击“播放”按钮,停止 Unity 应用 。Stop the Unity app by clicking the Play button again.

    停止 Unity 应用

  15. 返回 Visual Studio for Mac 。Return to Visual Studio for Mac. 单击“停止”按钮,停止调试会话 。Stop the debugging session by clicking the Stop button.

    在 Visual Studio for Mac 中停止调试会话

任务 4:在 Visual Studio for Mac 中探索 Unity 功能Task 4: Exploring Unity features in Visual Studio for Mac

  1. Visual Studio for Mac 提供在代码编辑器中快速访问 Unity 文档的功能。Visual Studio for Mac provides quick access to Unity documentation within the code editor. 将光标放在 Update 方法中 Vector3 符号的某处,然后按 ⌘ 命令+' 。Place the cursor somewhere on the Vector3 symbol within the Update method and press ⌘ Command + '.

    在 Visual Studio for Mac 编辑器中选择方法

  2. 针对 Vector3 的文档,打开新的浏览器窗口 。A new browser window opens to the documentation for Vector3. 满意后关闭浏览器窗口。Close the browser window when satisfied.

    针对文档打开浏览器窗口

  3. Visual Studio for Mac 还提供一些帮助程序用于快速创建 Unity 行为类。Visual Studio for Mac also provides some helpers to quickly create Unity behavior classes. 在“解决方案资源管理器”中,右键单击“资产”,然后依次选择“添加”、“新的 MonoBehaviour” 。From Solution Explorer, right-click Assets and select Add > New MonoBehaviour.

    新的 MonoBehaviour 上下文操作

  4. 新创建的类提供 Start 和 Update 方法的存根 。The newly created class provides stubs for the Start and Update methods. 在 Update 方法的右大括号之后,开始键入 onmouseup 。After the closing brace of the Update method, start typing "onmouseup". 键入时,请注意 Visual Studio 的 IntelliSense 会快速将你计划实施的方法归零。As you type, notice that Visual Studio's IntelliSense quickly zeros in on the method you're planning to implement. 从提供的自动完成列表中选择它。Select it from the provided autocomplete list. 它将为你填充方法存根,包括任何参数。It will fill out a method stub for you, including any parameters.

    Visual Studio for Mac 中的 IntelliSense

  5. 在 OnMouseUp 方法内,键入 base. Inside the OnMouseUp method, type "base." 查看可调用的所有基本方法。to see all of the base methods available to call. 还可以使用 IntelliSense 浮出控件右上角的分页选项,探索每个函数的不同重载。You can also explore the different overloads of each function using the paging option in the top-right corner of the IntelliSense flyout.

    在 Visual Studio for Mac 中探索重载

  6. Visual Studio for Mac 还使你可以轻松定义新的着色器。Visual Studio for Mac also enables you to easily define new shaders. 在“解决方案资源管理器”中,右键单击“资产”,然后依次选择“添加”、“新的着色器” 。From Solution Explorer, right-click Assets and select Add > New Shader.

    Visual Studio for Mac 中的新着色器操作

  7. 着色器文件格式获得全彩色和字体处理,便于阅读和理解。The shader file format gets full color and font treatment to make it easier to read and understand.

    语法突出显示

  8. 返回 Unity 。Return to Unity. 你将看到,由于 Visual Studio for Mac 使用相同的项目系统,因此在任一位置所做的更改将自动与另一位置同步。You'll see that since Visual Studio for Mac works with the same project system, changes made in either place are automatically synchronized with the other. 现可始终轻松地使用最佳工具来完成任务。Now it's easy to always use the best tool for the task.

    Unity 资产面板

总结Summary

在本实验室中,你已了解了如何使用 Unity 和 Visual Studio for Mac 开始创建游戏。In this lab, you've learned how to get started creating a game with Unity and Visual Studio for Mac. 有关 Unity 的详细信息,请参阅 https://unity3d.com/learnSee https://unity3d.com/learn to learn more about Unity.