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


  • 深入了解使用 Visual Studio for Mac 進行 Unity 開發Learn about Unity development with Visual Studio for Mac


目標對象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. 啟動 UnityLaunch Unity. 如果系統要求,請登入。Sign in if requested.

  2. 按一下 [新增]Click New.

    Unity 中的 [New] (新增) 按鈕

  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. 這些元件會附加到 GameObjectThese components are attached to a GameObject.

  7. 從 [Hierarchy] (階層) 窗格中選取 [Main Camera] (主相機) 物件。Select the Main Camera object from the Hierarchy pane.


  8. 從視窗右側選取 Inspector (屬性編輯器) 窗格以檢閱其屬性。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. 選取 [Directional Light] (定向光線) 物件。Select the Directional Light object. 這為場景提供了光線,因此著色器等元件知道如何轉譯物件。This provides light to the scene so that components like shaders know how to render objects.


  10. 使用 Inspector 可以看到它包含常見的光源屬性,包括類型、色彩、濃度、陰影類型等等。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. 在底部的 [Project] (專案) 索引標籤中,以滑鼠右鍵按一下 [Assets] (資產) 資料夾,然後選取 [Reveal in Finder] (在 Finder 中顯示)。In the Project tab on the bottom, right-click the Assets folder and select Reveal in Finder.

    在 Finder 內容動作中顯示

  12. 如您所見,Projects 包含 [Assets] (資產)、[Library] (程式庫)、[ProjectSettings] (專案設定) 和 [Temp] (暫存) 資料夾。Projects contain Assets , Library , ProjectSettings , and Temp folders as you can see. 不過,唯一在介面中顯示的是 [Assets] 資料夾。However, the only one that shows up in the interface is the Assets folder. [Library] 資料夾是匯入資產的本機快取,它會保留資產的所有中繼資料。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).

    在 Finder 中的 Assets

  13. 關閉 [Finder] 視窗並返回 UnityClose 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 中的 [Assets] 資料夾

  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 Object] (3D 物件) > [Cube] (立方體) 功能表將新的 Cube 物件新增至場景中。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. 此外,數個元件已連結至 Cube 以提供所需的功能,包括網格篩選條件,方塊碰撞器和轉譯器。In addition, several components were attached to the Cube to provide needed functionality including mesh filter, box collider, and renderer.


  17. Cube 物件 (預設名稱為 "Cube" ) 重新命名為 "Enemy"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. 使用與上面相同的程序將另一個 Cube 物件新增到場景中,並將其命名為 "Player"Add another Cube object to the scene using the same process as above, and name this one "Player".


  19. 也將玩家物件標記為 "Player" (請參閱 [名稱] 欄位下的 Tag (標記) 下拉式清單控制項)。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. 在 [Scene] (場景) 檢視中,使用滑鼠沿著 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. 這會更新 Inspector 中的 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 window and select Create > C# Script.

    C# 指令碼內容動作

  23. 將新的 C# 指令碼命名為 "EnemyAI"Name the new C# script "EnemyAI".

    C# 指令碼

  24. 若要將指令碼附加至遊戲物件,請將新建立的指令碼拖曳至 [Hierarchy] 窗格中的 Enemy 物件上。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. 選取 [File] (檔案) > [Save Scenes] (儲存場景) 以儲存目前場景。Select File > Save Scenes to save the current scene. 將它命名為 "MyScene"Name it "MyScene".

工作2:使用適用于 Unity 的 Visual Studio for Mac 工具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] > [Preferences] (喜好設定)。Select Unity > Preferences.

  2. 選取 [ 外部工具 ] 索引標籤。從 [ 外部腳本編輯器 ] 下拉式清單中,選取 [流覽] ,然後選取 [ 應用程式/Visual Studio ]。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 Preferences] (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. 它包含 [Assets] 資料夾 (來自 [Finder] 的相同資料夾) 和稍早建立的 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 中的方案視窗

  6. EnemyAI.cs 會在編輯器中開啟。EnemyAI.cs is open in the editor. 初始的指令碼僅包含 StartUpdate 方法的虛設常式。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)
                    "Could not find the main player. Ensure it has the player tag set.");
                _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. 您可以按一下目標行的編輯器邊界,或將游標放在該行上,然後按 F9You 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. 按一下 [開始偵錯] 按鈕或按 F5Click 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 ,然後按一下 [Run] (執行) 按鈕來開始遊戲。Return to Unity and click the Run button to start the game.

    Unity 中的 [Run] (執行) 按鈕

  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.cs 物件的 this 指標。From the Locals window, locate the this pointer, which references an EnemyAI object. 展開參考,並查看您可以瀏覽相關聯的成員,例如 [Speed] (速度)。Expand the reference and see that you can browse the associated members like Speed.

    Visual Studio for Mac 中的 [區域變數] 視窗

  6. Start 方法中移除中斷點,方法與新增它的方式相同 - 透過在邊界中按一下它,或選取行並按 F9Remove 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 不進入使用標記作為參數尋找 Player 遊戲物件的第一行程式碼。Press F10 to step over the first line of code that finds the Player game object using a tag as parameter.

  8. 將滑鼠游標暫留在程式碼編輯器視窗中的 player 變數上,以檢視其相關聯的成員。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. 在 [自動變數] 或 [區域變數] 視窗中找到 Speed 變數,然後將它變更為 "10" 並按 EnterLocate 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. 再次按一下 [Play] (播放) 按鈕停止 Unity 應用程式。Stop the Unity app by clicking the Play button again.

    停止 Unity 應用程式

  15. 返回 Visual Studio for MacReturn 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 符號上的某處,然後按 ⌘ Command + '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. 新建立的類別會為 StartUpdate 方法提供虛設常式。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. 返回 UnityReturn 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 資產面板


在此實驗室中,您已了解如何開始使用 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. https://unity3d.com/learn若要深入瞭解 Unity,請參閱。See https://unity3d.com/learn to learn more about Unity.