Перейти к содержимому

Как настроить visual studio code для c unity

  • автор:

Unity Development with VS Code

Visual Studio Code can be a great companion to Unity for editing and debugging C# files. All of the C# features are supported and more. In the screen below you can see code colorization, bracket matching, IntelliSense, Code Lens and that’s just the start.

Read on to find out how to configure Unity and your project to get the best possible experience.

Note: VS Code uses a more recent version of Mono than that included with Unity. If you get OmniSharp errors, you may need to update your Mono version. See this FAQ topic for additional details.

Connecting Unity and VS Code

The easiest way to get going is to leverage a Unity plug-in maintained by @@Reapazor. This plug-in streamlines the integration process significantly by performing the following tasks:

  1. Sets VS Code as the default editor — opening a script now opens it in VS Code
  2. Configures Unity to pass file and line numbers and reuse the existing window — so VS Code opens in the correct context
  3. Scrubs the Unity project file to ensure that OmniSharp can work with it — to get the best editing experience
  4. Configures VS Code to ignore certain Unity file types — removing clutter from the VS Code file explorer
  5. Configures a launch.json file with the correct debug port — to enable debugging

Note: Debugging support is only offered on OS X today. Windows does not support debugging via Mono. We have also not done any significant testing of the plug-in with the Linux Unity build.

Step 1: Download the plug-in code

Open up a console and do a clone of the repo to get the plug-in source code.

Step 2: Add the plug-in to your project

Go to the folder where you downloaded the plug-in source code and copy the Plugins\Editor\dotBunny folder to your Unity project.

Tip: You may need to create a Plugins folder. Typically this should be stored under Assets .

To turn on the use of the provided integration you will need to go to Unity Preferences and select the newly created VSCode tab.

VSCode Preferences

Toggle on Enable Integration and you are ready to get going.

Additionally, you can toggle Output Messages To Console which will echo output to the Unity console e.g. whether the debug port was found. This is useful for debugging any issues with the integration.

Clicking the Write Workspace Settings button will configure the workspace settings to filter out non-code assets created by Unity e.g. .meta files.

Step 3: Open the Project

Now available in the Assets menu is Open C# Project In Code . This will open the project in VS Code in the context of the root folder of your project. This enables VS Code to find your Unity project’s solution file.

VSCode Menu

Tip: You probably want to leave a VS Code window open with the project context established. That way when you open a file from Unity it will have all the required context.

Editing Evolved

With the solution file selected, you are now ready to start editing with VS Code. Here is a list of some of the things you can expect:

  • Syntax Highlighting
  • Bracket matching
  • IntelliSense
  • Snippets
  • Code Lens
  • Peek
  • Go-to Definition
  • Code Actions/Lightbulbs
  • Go to symbol
  • Hover

Two topics that will help you are Editing Evolved and C#. In the image below, you can see VS Code showing hover context, peeking references and more.

editing evolved

Next Steps

Read on to learn more about:

    — find out more about the evolved editing features — how to use the debugger with your project — learn about the C# support in VS Code

Common Questions

Q: I don’t have IntelliSense.

A: You need to ensure that your solution is open in VS Code (not just a single file). Open the folder with your solution and you usually will not need to do anything else. If for some reason VS Code has not selected the right solution context, you can change the selected project by clicking on the OmniSharp flame icon on the status bar.

Flame

Choose the -CSharp version of the solution file and VS Code will light up.

Choose Solution

Q: How can I manually configure Editor Settings?

A: To set VS Code as the External Editor for Unity go to the Edit | Preferences. menu. From there move to the External Tools tab where you should see a screen like the following:

External Editor settings

Click the browse button and set the VS Code executable (under Program Files (x86)\Microsoft VS Code\Code.exe ) as the External Script Editor.

This will enable Unity to launch VS Code whenever you open a script.

Q: I want to set the command line arguments when I launch VS Code.

A: The workflow between Unity and VS Code is much smoother if you reopen an existing editor window and pass in context so that the editor lands on the exact line number and column location (for example to navigate to a compile bug).

Note: This option is only available in the Windows version of Unity. For Mac users, the Unity plug-in described above handles setting up the command line arguments.

To configure Unity to pass this data to VS Code, set the Editor Args to be -r -g «$(File):$(Line) . You can see this step completed in the image above.

Q: How can I change the file exclusions?

A: Unity creates a number of additional files that can clutter your workspace in VS Code. You can easily hide these so that you can focus on the files you actually want to edit.

To do this, add the following JSON to your workspace settings.

As you can see below this will clean things up a lot.

Before After
Filtered files ee

Q: VS Code did not go the correct position in my file.

A: For OS X, make sure you have installed the Unity plug-in described above. For Windows, ensure you have set the additional command line arguments when you launch VS Code from Unity.

Q: How can I debug Unity?

A: To get debugging to work, you need to configure VS Code to use the Mono debugger.

Note: Debugging is only supported via Mono. As a result, this section only applies to Mac OS X (the Linux version of Unity should also work but is not tested).

How to Use Visual Studio Code with Unity

Unity has MonoDevelop as a built-in code editor. But not many developers love it. Among many alternatives of MonoDevelop, Visual Studio Code is a good choice for editing and debugging Unity’s C# files.

Table of Contents

Download Visual Studio Code

You can download the stable build directly from Visual Studio website. In case you want to test new features which are being built, VS Code Insiders should be your choice.

Set VS Code as default script editor

In Unity, open Unity’s preferences window by access Edit > Preferences. Then on External Tools, browse to the folder VS Code was installed in order to set it as default external script editor. After that, double-clicking on a script file will open it in this editor.

VS Code supports most common features of a script editor such as Syntax Highlighting, IntelliSense, Snippets, and CodeLens.

Install Unity Extensions

Before using the editor, you need to install some extensions from VS Code Extension Marketplace, which will help you writing code for Unity faster.

In VS Code, open Extension tabs or press Ctrl + Shift + X then type “Unity” in the search box to search for all extensions related to Unity. There are 3 extensions you need to install.

Unity Development with VS Code

Visual Studio Code can be a great companion to Unity for editing C# files. All of the C# features are supported and more. In the screen below, you can see code colorization, bracket matching, IntelliSense, CodeLens and that’s just the start.

Read on to find out how to configure Unity and your project to get the best possible experience.

Prerequisites

Install the .NET SDK, which includes the Runtime and the dotnet command.

[Windows only] Logout or restart Windows to allow changes to %PATH% to take effect.

[macOS only] To avoid seeing "Some projects have trouble loading. Please review the output for more details", make sure to install the latest stable Mono release.

Note: This version of Mono, which is installed into your system, will not interfere with the version of MonoDevelop that is installed by Unity.

Install the C# extension from the VS Code Marketplace.

In the VS Code Settings editor ( ⌘, (Windows, Linux Ctrl+, ) ), uncheck the C# extension’s Omnisharp: Use Modern Net setting ( "omnisharp.useModernNet": false ).

Install Build Tools for Visual Studio (Windows only)

The C# extension no longer ships with Microsoft Build Tools so they must be installed manually.

  1. Download the Build Tools for Visual Studio 2022.
  2. Install the .NET desktop build tools workload. No other components are required.

Setup VS Code as Unity Script Editor

Open up Unity Preferences, External Tools, then browse for the Visual Studio Code executable as External Script Editor.

The Visual Studio Code executable can be found at /Applications/Visual Studio Code.app on macOS, %localappdata%\Programs\Microsoft VS Code\Code.exe on Windows by default.

Unity has built-in support for opening scripts in Visual Studio Code as an external script editor on Windows and macOS. Unity will detect when Visual Studio Code is selected as an external script editor and pass the correct arguments to it when opening scripts from Unity. Unity will also set up a default .vscode/settings.json with file excludes, if it does not already exist (from Unity 5.5 Release notes).

Unity version 2019.2 or above

Since 2019.2, it is required to use the Visual Studio Code Editor package. The built-in support for opening scripts from Unity and getting csproj and sln files generated has been removed.

Editing Evolved

With the solution file selected, you are now ready to start editing with VS Code. Here is a list of some of the things you can expect:

  • Syntax Highlighting
  • Bracket matching
  • IntelliSense
  • Snippets
  • CodeLens
  • Peek
  • Go-to Definition
  • Code Actions/Lightbulbs
  • Go to symbol
  • Hover

Two topics that will help you are Basic Editing and C#. In the image below, you can see VS Code showing hover context, peeking references and more.

editing evolved example

Enabling code completion (For recent versions of Unity)

If you are installing VS Code for the first time, you might be missing targeting packs required for Unity’s code-completion (IntelliSense) in VS Code.

Targeting pack download links:

  1. Stop VS Code or Unity running.
  2. Download and install the targeting pack for your targeted framework version / preferred version from one of the above links.
  3. Start Unity.
  4. Create and/or open an existing script in VS Code, through Unity, and you should now see code completions.

Enabling Unity warnings

Unity has a set of custom C# warnings, called analyzers, that check for common issues with your source code. These analyzers ship out of the box with Visual Studio but need to be set up manually in Visual Studio Code.

Due to how Unity handles its .csproj files, it does not seem possible to install packages automatically. You will need to download the analyzers from the NuGet website manually. Make sure to download the .nupkg file, the source code from GitHub will not work.

When you’re done, open the package file using a tool such as 7zip and extract Microsoft.Unity.Analyzers.dll onto your project’s root folder. You can place it inside a folder named NuGet , for example. Do not place it inside Assets or Packages , as that will cause Unity to try to process the .dll , which will make it output an error in the console.

Note: 7zip cannot open a .nupkg file by right-click and Open with. Instead, you have to open the 7zip application, navigate to the file, and then select Extract.

Next, create an omnisharp.json file at the root folder of your project, as explained here. Analyzer support in OmniSharp is experimental at the moment, so we need to enable it explicitly. We also need to point it to the .dll file we just extracted.

Your omnisharp.json file should end up looking like this:

where "./NuGet/microsoft.unity.analyzers.1.14.0/analyzers/dotnet/cs" is a relative path pointing to the folder containing the .dll file. Depending on where you placed it, your path may look different.

The Unity analyzers should now be working in your project. You can test them by creating an empty FixedUpdate() method inside one of your MonoBehavior classes, which should trigger a The Unity message ‘FixedUpdate’ is empty warning (UNT0001).

Note that while it is possible to activate these analyzers, the suppressors they ship with the package (that turn off other C# warnings that may conflict with these custom ones) may not be picked up by OmniSharp at the moment, according to this thread. You can still turn off specific rules manually by following these steps:

  1. Create a .editorconfig file in your project’s root folder (next to Unity’s .csproj files).
  2. Add the following contents to the file:

root=true tells OmniSharp that this is your project root and it should stop looking for parent .editorconfig files outside of this folder.

dotnet_diagnostic.IDE0051.severity = none is an example of turning off the analyzer with ID IDE0051 by setting its severity level to none . You can read more about these settings in the Analyzer overview. You can add as many of these rules as you want to this file.

[*.cs] indicates that our custom rules should apply to all C# scripts (files with the .cs extension).

You are now ready to code in Visual Studio Code, while getting the same warnings as you would when using Visual Studio!

Next steps

Read on to learn more about:

    — Learn about the powerful VS Code editor. — Move quickly through your source code. — learn about the C# support in VS Code

Common questions

I don’t have IntelliSense

You need to ensure that your solution is open in VS Code (not just a single file). Open the folder with your solution and you usually will not need to do anything else. If for some reason VS Code has not selected the right solution context, you can change the selected project by clicking on the OmniSharp flame icon on the status bar.

OmniSharp Flame on the Status Bar

Choose the -CSharp version of the solution file and VS Code will light up.

Choose Solution

How can I change the file exclusions?

Unity creates a number of additional files that can clutter your workspace in VS Code. You can easily hide these so that you can focus on the files you actually want to edit.

To do this, add the following JSON to your workspace settings. By adding these excludes to your workspace settings, you will not change your global user settings and it allows anyone also working on the project to have the same file excludes.

As you can see below this will clean things up a lot.

Before After
Unfiltered files filtered files

To edit this directly within VS Code Settings editor, go to File > Preferences > Settings (Code > Preferences > Settings on macOS). Switch to the Workspace tab and then type "files exclude" into the Settings editor search bar. Add a glob pattern similar to the pattern shown below by clicking the Add Pattern button for the Files: Exclude setting. You will need to add each pattern separately.

Debug C# code in Unity

You can use a debugger to inspect your source code while your application is running. Unity supports the following code editors to debug C# code:

  • Visual Studio (with the Visual Studio Tools for Unity plug-in)
  • Visual Studio for Mac
  • Jetbrains Rider
  • Visual Studio Code (experimental)

Although these code editors vary slightly in the debugging features they support, they all provide basic functionality such as break points, single stepping, and variable inspection. You can attach these code editors to the Unity Editor or Unity Player to debug your code.

Managed code debugging in Unity works on all platforms except WebGL A JavaScript API that renders 2D and 3D graphics in a web browser. The Unity WebGL build option allows Unity to publish content as JavaScript programs which use HTML5 technologies and the WebGL rendering API to run Unity content in a web browser. More info
See in Glossary . It works with both the Mono A scripting backend used in Unity. More info
See in Glossary and IL2CPP A Unity-developed scripting back-end which you can use as an alternative to Mono when building projects for some platforms. More info
See in Glossary scripting backends A framework that powers scripting in Unity. Unity supports three different scripting backends depending on target platform: Mono, .NET and IL2CPP. Universal Windows Platform, however, supports only two: .NET and IL2CPP. More info
See in Glossary .

Configure the code editor

Visual Studio (Windows)

The Unity Editor installer includes an option to install Visual Studio with the Visual Studio Tools for Unity plug-in A set of code created outside of Unity that creates functionality in Unity. There are two kinds of plug-ins you can use in Unity: Managed plug-ins (managed .NET assemblies created with tools like Visual Studio) and Native plug-ins (platform-specific native code libraries). More info
See in Glossary
. This is the recommended way to set up Visual Studio for debugging with Unity.

If Visual Studio is already installed on your computer, open it and go to Tools > Get Tools and Features… to locate and install the Visual Studio Tools for Unity plug-in.

Visual Studio for Mac

The Unity Editor installer includes an option to install Visual Studio for Mac. This is the recommended way to set up Visual Studio for Mac for debugging with Unity.

If Visual Studio for Mac is already installed on your computer, open it and go to Visual Studio > Extensions > Install from file… to locate and install the Visual Studio Tools for Unity plug-in.

JetBrains Rider

You can use the default installation of JetBrains Rider to debug code in Unity on Windows or Mac. Visit the JetBrains website to install it.

Visual Studio Code

To debug in Unity using Visual Studio Code, you need to install an extension. See Visual Studio Code’s documentation to configure Visual Studio Code as the code editor for your Unity project. Follow Visual Studio Code’s instructions specific to the Debugger for Unity extension to install it. Unity’s support for Visual Studio Code is experimental as Unity does not officially support the Debugger for Unity extension.

Specify the External Script Editor in Unity

Once you’ve installed a code editor, open Unity, go to Preferences > External Tools and set the External Script Editor to your code editor.

The External Tools settingsThe External Tools settings

Breakpoints

Breakpoints allow you to specify points in your code where you want to pause its execution. In your external code editor, you can set a breakpoint on a line of code where you want the debugger to stop. While the code editor is at a breakpoint, you can view the contents of variables step by step.

If you have attached your code editor to the Unity Editor (see Attach your code editor to the Unity Editor), the Unity Editor becomes unresponsive until you choose the continue option in your code editor, or stop debugging mode.

To see how you can set breakpoints in Visual Studio see Set breakpoints in Visual Studio.

Debug in the Unity Editor

You can debug C# code as it runs in the Unity Editor while the Unity Editor is in Play Mode.

To debug in the Editor, you need to set the Editor’s Code Optimization mode to Debug Mode, then you can attach a code editor with a debugging feature.

To change the Code Optimization mode, select the Debug Button in the bottom right of the Unity Editor Status Bar.

The Debug Button in the bottom right of the Unity Editor Status BarThe Debug Button in the bottom right of the Unity Editor Status Bar

Unity’s Code Optimization setting has two modes:

  • Debug Mode, which you can use to attach external debugger software, but gives slower C# performance when you run your Project in Play Mode in the Editor.
  • Release Mode, which gives faster C# performance when you run your Project in Play Mode in the Editor, but you cannot attach any external debuggers.

When you click the Debug button in the status bar, a small pop-up window opens which contains a button you can use to switch modes. The window also displays information about the current mode, and describes what happens if you switch modes.

The Debug Mode popup, which shows the current mode, allows you to switch modes, and describes what happens if you switch mode.The Debug Mode popup, which shows the current mode, allows you to switch modes, and describes what happens if you switch mode.

To change which mode the Unity Editor starts up in, go to Edit (macOS: Unity) > Preferences > General > Code Optimization On Startup.

In Preferences, you can change the Code Optimization mode that Unity starts in.In Preferences, you can change the Code Optimization mode that Unity starts in.

To control these settings using a script, use the following API:

You can also override the mode that the Editor starts up in, or turn off the debugger listen socket. To do this, use the following command line arguments when you launch the Editor:

  • -releaseCodeOptimization . Starts the Editor in Release code optimization mode.
  • -debugCodeOptimization . Starts the Editor in Debug code optimization mode.
  • -disableManagedDebugger . Starts the Editor with the debugger listen socket disabled.

Attach your code editor to the Unity Editor

The way to attach your code editor to the Unity Editor depends on what code editor you use, and is often a different option from your code editor’s normal debugging process. Some code editors allow you to select an instance of Unity to debug. For instructions specific to your code editor, see Code editor external documentation. To see how you can do this in Visual Studio, see Attach Visual Studio to the Unity Editor.

When you have attached the code editor to the Unity Editor and you are ready to begin debugging, return to the Unity Editor and enter Play Mode.

Debug in the Unity Player

To compile a Unity Player for you to debug:

  1. Go to File > Build Settings.
  2. Enable the Development Build A development build includes debug symbols and enables the Profiler. More info
    See in Glossary
    and Script Debugging options before you build the Player. You could also enable the Wait For Managed Debugger option to make the Player wait for a debugger to be attached before the Player executes any script code.
  3. Select Build And Run.

Attach your code editor to the Unity Player

To attach your code editor to the Unity Player, in your code editor, select the IP address (or machine name) and port of your Player. For an example of where to find this in Visual Studio, see Attach Visual Studio to the Unity Editor.

Note: Your code editor will show all instances of Unity that are available to debug. Make sure you attach the code editor to the correct instance of the Unity Player, and not to the Unity Editor if both are running.

When you have attached the debugger, you can begin debugging normally. For instructions on how to attach the Unity Player to your specific code editor, see Code editor external documentation. For an example of how to attach a Unity Player that runs on a mobile device to Visual Studio, see Debug Android and iOS devices with Visual Studio.

Set breakpoints in Visual Studio

To set a breakpoint in Visual Studio, click on the column to the left of your code, on the line you want to stop the debugger. A red circle appears next to the line number and the line is highlighted.

A breakpoint in Visual Studio.A breakpoint in Visual Studio.

Attach Visual Studio to the Unity Editor

To attach the Unity Editor to your Visual Studio script, open Visual Studio, go to Debug > Attach Unity Debugger and select the instance of the Unity Editor you would like to debug.

In the following example image, there is one instance of Unity running in the Editor and one instance of Unity running as an Android Player

Visual Studio lists the current instances of Unity that are available to debug.Visual Studio lists the current instances of Unity that are available to debug.

Debug Android and iOS devices with Visual Studio

Android

To debug a Unity Player running on an Android device, connect to the device using USB or TCP. For example, to connect to an Android device in Visual Studio, select Debug > Attach Unity Debugger option. A list of devices running a Player instance appears.

In this example, the android device is connected using USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.

Android on Chrome OS

Unity can’t automatically discover Chrome OS devices. To initiate a connection, connect to the device through Android Debug Bridge (adb). For more information about how to use adb An Android Debug Bridge (ADB). You can use an ADB to deploy an Android package (APK) manually after building. More info
See in Glossary , see the Android Studio User Guide.

To debug a Unity Player running on an iOS device, connect to the device using TCP. For example, to connect to an iOS device in Visual Studio for Mac, select Debug > Attach Unity Debugger. A list of devices running a Player instance appears.

Ensure that the device only has one active network interface (Wi-Fi recommended, turn off cellular data) and that there is no firewall between the IDE and the device blocking the TCP port (port number 56000 in the above screenshot).

Important: iOS Apple’s mobile operating system. More info
See in Glossary does not support debugging over USB.

Troubleshoot the debugger

Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Unity Player. This means that the Unity Editor or Player can’t attach the debugger properly. Because the debugger uses a TCP connection to the Editor or Player, connection issues are often caused by the network. Below are a few steps you can take to troubleshoot basic connection issues.

Ensure you attach the debugger to the correct Unity instance

You can attach your code editor to any instance of the Unity Editor or Unity Player on the local network that has debugging enabled. When you attach the debugger, ensure that you attach it to the correct Unity instance. If you know the IP address or machine name of the device on which you are running the Unity Player, this helps to locate the correct instance.

Verify the network connection to the Unity instance

The code editor uses the same mechanism to locate a Unity instance to debug as the Unity Profiler A window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating, or in your game logic. More info
See in Glossary . If the code editor can’t find the Unity instance you expect, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find the Unity instance either, there might be a firewall on the machine you are running the code editor or Unity instance on. If a firewall is in place, see Check the firewall settings.

Ensure the device only has one active network interface

Many devices have multiple network interfaces. For example, a mobile phone might have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger to the Unity instance using TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug over Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.

You can determine which IP address the Unity Player tells the IDE to use by looking in the Player Log The .log file created by a Standalone Player that contains a record of events, such as script execution times, the compiler version, and AssetImport time. Log files can help diagnose problems. More info
See in Glossary . Look for a part of the log like this:

Multi-casting "[IP] 10.0.1.152 [Port] 55000 [Flags] 3 [Guid] 2575380029 [EditorId] 4264788666 [Version] 1048832 [Id] iPhonePlayer(Example-iPhone):56000 [Debug] 1 [PackageName] iPhonePlayer" to [225.0.0.222:54997].

This message indicates the IDE will try to use the IP address 10.0.1.152 and port 56000 to connect to the device. This IP address and port must be reachable from the computer running the IDE.

Check the firewall settings

The Unity instance communicates with the code editor using a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you shouldn’t need to know this port, as the code editor should detect it automatically. If that doesn’t work, use a network analysis tool to determine which ports might be blocked either on the machine where you are running the code editor, or the machine or device where you are running the Unity instance. When you find the ports, make sure that your firewall allows access to the port on both the machine running the code editor, and the machine running the Unity instance.

Verify the managed debugging information is available

If the debugger attaches to the Unity instance but breakpoints don’t load, the debugger might not be able to locate the managed debugging information for the code. Managed code debugging information is stored in files named .pdb, next to the managed assembly (.dll file) on the disk.

When you enable the correct preferences and build options (see Configure the code editor), Unity generates this debugging information automatically. However, Unity cannot generate debugging information for managed plugins in your project. You can only debug code from managed plugins if the associated .pdb files are next to the managed plugins in the Unity project on disk.

Prevent the device from locking

Disable any screen locks on the device you are using to debug your application. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. Don’t lock the screen during managed code debugging. If the screen locks, restart the application on the device so the debugger can connect again.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *