Unity как изменить редактор кода

Setting Up Your Scripting Environment

Setting Up Your Scripting Environment

An integrated development environment (IDE) is a piece of computer software that provides tools and facilities to make it easier to develop other pieces of software. Unity supports the following IDEs:

  • Visual Studio
  • Visual Studio Code
  • JetBrains Rider

Visual Studio (default IDE on Windows and macOS)

When you install Unity on Windows and macOS, by default Unity also installs Visual Studio or Visual Studio for Mac, respectively. You can choose to exclude it when you select which components to download and install. By default, the External Script Editor (menu: Unity > Preferences > External Tools > External Script Editor) is set to Visual Studio. When you enable this option, Unity launches Visual Studio and uses it as the default editor for all script files. For more information, see Visual Studio C# Integration.

On macOS, Unity installs Visual Studio for Mac as the C# IDE. Visual Studio Tools for Unity (VSTU) provides Unity integration for Visual Studio for Mac (VS4M). For information on setting up and using Visual Studio for Mac, see the following Microsoft documentation pages:

  • Visual Studio Tools for Unity
  • Setup Visual Studio for Mac Tools for Unity
  • Using Visual Studio for Mac Tools for Unity

Note: On Windows, Unity also includes Visual Studio 2019 Community by default in the installation package.

Visual Studio Code (Windows, macOS, Linux)

Unity supports opening scripts in Visual Studio Code (VS Code). To open scripts in VS Code, go to Unity > Preferences > External Tools > External Script Editor and select Visual Studio Code. For information on using VS Code with Unity, see Visual Studio’s documentation on Unity Development with VS Code.

Prerequisites

To use Visual Studio Code for C# code editing and Unity C# debugging support, you need to install:

  • MonoA scripting backend used in Unity. More info
    See in Glossary
    (only required on macOS and Linux)
  • Visual Studio Code C# Extension
  • Visual Studio Code Debugger for Unity Extension (Not officially supported by Unity)

JetBrains Rider (Windows, macOS, Linux)

Unity supports opening scripts in JetBrains Rider. To open scripts in Rider, go to Unity > Preferences > External Tools > External Script Editor and select Rider.

Rider is based on ReSharper and includes most of its features. It supports all of C# 7.2’s features as well as C# debugging on the .NET 4.6 scripting runtime in Unity. For more information, see JetBrains’ documentation on Rider for Unity.


  • 2019–04–18 Page published

Setting Up Your Scripting Environment

Интегрированная среда разработки (IDE) – это часть компьютерного программного обеспечения, предоставляющая инструменты и средства, облегчающие разработку других частей программного обеспечения. Unity поддерживает следующие IDE:

  • Visual Studio
  • Код Visual Studio
  • Руководитель JetBrains

Visual Studio (IDE по умолчанию в Windows и macOS)

При установке Unity в Windows и macOS по умолчанию Unity также устанавливает Visual Studio или Visual Studio для Mac соответственно. Вы можете исключить его при выборе компонентов для загрузки и установки. По умолчанию Редактор внешних скриптов (меню: Unity > Настройки > Внешние инструменты > Внешний скрипт Редактор) настроен на Visual Studio. Когда вы включаете эту опцию, Unity запускает Visual Studio и использует ее в качестве редактора по умолчанию для всех файлов сценариев. Дополнительные сведения см. в разделе Интеграция Visual Studio C#.

В macOS Unity устанавливает Visual Studio для Mac в качестве C# IDE. Инструменты Visual Studio для Unity (VSTU) обеспечивают интеграцию Unity с Visual Studio для Mac (VS4M). Сведения о настройке и использовании Visual Studio для Mac см. на следующих страницах документации Microsoft:

  • Инструменты Visual Studio для Unity
  • Настройка инструментов Visual Studio для Mac для Unity
  • Использование инструментов Visual Studio для Mac для Unity

Примечание. В Windows Unity также включает Visual Studio 2019 Community. по умолчанию в установочном пакете.

Код Visual Studio (Windows, macOS, Linux)

Unity поддерживает открытие скриптов в Visual Studio Code (VS Code). Чтобы открыть скрипты в VS Code, перейдите в Unity > Настройки > Внешние инструменты > Редактор внешних скриптов и выберите < b>Код Visual Studio. Информацию об использовании VS Code с Unity см. в документации Visual Studio по Разработка Unity с VS Code. .

Предпосылки

Чтобы использовать Visual Studio Code для редактирования кода C# и поддержку отладки Unity C#, необходимо установить:

  • МоноA серверная часть сценариев, используемая в Unity. Подробнее
    См. в Словарь
    (требуется только в macOS и Linux)
  • Расширение Visual Studio Code C#
  • Отладчик кода Visual Studio для расширения Unity (официально не поддерживается Unity)< /li>

JetBrains Rider (Windows, macOS, Linux)

Unity поддерживает открытие скриптов в JetBrains Rider. Чтобы открыть скрипты в Rider, перейдите в Unity > Настройки > Внешние инструменты > Редактор внешних скриптов и выберите Всадник.

Rider основан на ReSharper и включает большинство его функций. Он поддерживает все функции C# 7.2, а также отладку C# в среде выполнения сценариев .NET 4.6 в Unity. Дополнительную информацию см. в документации JetBrains по Rider for Unity.

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.

Unity Example

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

Prerequisites

From Using .NET in Visual Studio Code:

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

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

  3. [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.

  4. Install the C# extension from the VS Code Marketplace.

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

Unity Preferences

The Visual Studio Code executable can be found at /Applications/Visual Studio Code.app on macOS, %localappdata%ProgramsMicrosoft VS CodeCode.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:

  • Windows: .NET Framework 4.7.1 Developer Pack
  • macOS: Download .NET SDK

Steps:

  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:

{
  "RoslynExtensionsOptions": {
    "EnableAnalyzersSupport": true,
    "LocationPaths": ["./NuGet/microsoft.unity.analyzers.1.14.0/analyzers/dotnet/cs"]
  }
}

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

[*.cs]
dotnet_diagnostic.IDE0051.severity = none

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:

  • Basic Editing — Learn about the powerful VS Code editor.
  • Code Navigation — Move quickly through your source code.
  • C# — 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.

    // Configure glob patterns for excluding files and folders.
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.meta": true,
        "**/*.*.meta": true,
        "**/*.unity": true,
        "**/*.unityproj": true,
        "**/*.mat": true,
        "**/*.fbx": true,
        "**/*.FBX": true,
        "**/*.tga": true,
        "**/*.cubemap": true,
        "**/*.prefab": true,
        "**/Library": true,
        "**/ProjectSettings": true,
        "**/Temp": true
    }

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.

**/.git
**/*.fbx
**/*.FBX
**/*.mat
**/*.*.meta
**/*.meta
**/*.prefab
**/*.unityproj
**/Library
**/Packages
**/ProjectSettings
**/Temp

11/4/2022

Order Area TOCTitle ContentId PageTitle DateApproved MetaDescription

3

other

Unity

75CD2FA6-2F91-428A-A88D-880611AE75A0

Visual Studio Code and Unity

11/4/2022

Visual Studio Code can replace MonoDevelop as the editor for Unity

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.

Unity Example

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

Prerequisites

From Using .NET in Visual Studio Code:

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

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

  3. [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.

  4. Install the C# extension from the VS Code Marketplace.

  5. In the VS Code Settings editor (kb(workbench.action.openSettings)), 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.

Unity Preferences

The Visual Studio Code executable can be found at /Applications/Visual Studio Code.app on macOS, %localappdata%ProgramsMicrosoft VS CodeCode.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:

  • Windows: .NET Framework 4.7.1 Developer Pack
  • macOS: Download .NET SDK

Steps:

  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:

{
    "RoslynExtensionsOptions": {
        "EnableAnalyzersSupport": true,
        "LocationPaths": [
            "./NuGet/microsoft.unity.analyzers.1.14.0/analyzers/dotnet/cs"
        ]
    }
}

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

[*.cs]
dotnet_diagnostic.IDE0051.severity = none

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:

  • Basic Editing — Learn about the powerful VS Code editor.
  • Code Navigation — Move quickly through your source code.
  • C# — 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.

    // Configure glob patterns for excluding files and folders.
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.meta": true,
        "**/*.*.meta": true,
        "**/*.unity": true,
        "**/*.unityproj": true,
        "**/*.mat": true,
        "**/*.fbx": true,
        "**/*.FBX": true,
        "**/*.tga": true,
        "**/*.cubemap": true,
        "**/*.prefab": true,
        "**/Library": true,
        "**/ProjectSettings": true,
        "**/Temp": true
    }

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.

**/.git
**/*.fbx
**/*.FBX
**/*.mat
**/*.*.meta
**/*.meta
**/*.prefab
**/*.unityproj
**/Library
**/Packages
**/ProjectSettings
**/Temp
Order Area TOCTitle ContentId PageTitle DateApproved MetaDescription

3

other

Unity

75CD2FA6-2F91-428A-A88D-880611AE75A0

Visual Studio Code and Unity

11/4/2022

Visual Studio Code can replace MonoDevelop as the editor for Unity

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.

Unity Example

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

Prerequisites

From Using .NET in Visual Studio Code:

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

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

  3. [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.

  4. Install the C# extension from the VS Code Marketplace.

  5. In the VS Code Settings editor (kb(workbench.action.openSettings)), 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.

Unity Preferences

The Visual Studio Code executable can be found at /Applications/Visual Studio Code.app on macOS, %localappdata%ProgramsMicrosoft VS CodeCode.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:

  • Windows: .NET Framework 4.7.1 Developer Pack
  • macOS: Download .NET SDK

Steps:

  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:

{
    "RoslynExtensionsOptions": {
        "EnableAnalyzersSupport": true,
        "LocationPaths": [
            "./NuGet/microsoft.unity.analyzers.1.14.0/analyzers/dotnet/cs"
        ]
    }
}

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

[*.cs]
dotnet_diagnostic.IDE0051.severity = none

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:

  • Basic Editing — Learn about the powerful VS Code editor.
  • Code Navigation — Move quickly through your source code.
  • C# — 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.

    // Configure glob patterns for excluding files and folders.
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.meta": true,
        "**/*.*.meta": true,
        "**/*.unity": true,
        "**/*.unityproj": true,
        "**/*.mat": true,
        "**/*.fbx": true,
        "**/*.FBX": true,
        "**/*.tga": true,
        "**/*.cubemap": true,
        "**/*.prefab": true,
        "**/Library": true,
        "**/ProjectSettings": true,
        "**/Temp": true
    }

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.

**/.git
**/*.fbx
**/*.FBX
**/*.mat
**/*.*.meta
**/*.meta
**/*.prefab
**/*.unityproj
**/Library
**/Packages
**/ProjectSettings
**/Temp

Понравилась статья? Поделить с друзьями:
  • Unity как изменить разрешение экрана
  • Unity как изменить разрешение камеры
  • Unity как изменить размер сетки
  • Unity как изменить размер объекта через скрипт
  • Unity как изменить размер terrain