Visual studio code unity
Visual studio code unity
Visual Studio C# integration
Unity integrates with Microsoft Visual Studio through the Code Editor Package for Visual Studio. This package is pre-installed when you install Unity. If Visual Studio is installed at the time you install Unity, then Unity uses Visual Studio to open and edit scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary by default.
The Visual Studio Editor in the Package Manager Window
Set Visual Studio as your default script editor
Unity automatically uses Visual Studio as its default script editor if Visual Studio is installed when you install Unity, or if you install Visual Studio as part of the Unity installation process. You can install Visual Studio as a module into an existing Unity installation. For more information, see Downloading and installing Editors and modules with the Unity Hub.
To set your default script editor manually:
A: The External Script Editor dropdown menu, which displays the name and version of the selected script editor.
B: The name and version of the Unity package that integrates with the selected script editor.
Unity uses Visual Studio’s C# compiler to compile scripts. When you use the Visual Studio Editor package with Visual Studio, both Unity and Visual Studio display details of any errors in your scripts.
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
[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.
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 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:
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.
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:
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.
Your omnisharp.json file should end up looking like this:
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:
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:
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.
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 |
---|---|
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.
Краткое руководство. Настройка Visual Studio для кроссплатформенной разработки с использованием Unity
Для Visual Studio Code & Unity ознакомьтесь с документацией по разработке Unity с VS Code.
Установка Visual Studio и Unity
Загрузите установщик Visual Studio или запустите его (если он был ранее установлен).
Выберите «Установить» или «Изменить«, если Visual Studio уже установлен.
На вкладке Рабочие нагрузки выберите рабочую нагрузку Разработка игр с помощью Unity.
Если Unity еще не установлен, выберите Unity Hub в разделе «Необязательно«.
Щелкните Изменить или Установить, чтобы завершить установку.
Когда Visual Studio завершит процесс установки, вы можете настроить Unity.
Откройте программу Unity Hub, которая была установлена во время установки Инструментов Visual Studio для Unity.
В левой части окна Unity Hub откройте вкладку Установки.
Нажмите кнопку Добавить.
В окне «Добавление версии Unity » выберите версию Unity для установки.
Нажмите кнопку Далее, чтобы продолжить установку.
На шаге Добавление модулей к установке выберите Готово.
Если вы уже установили Visual Studio 2022, можно отменить выбор параметра Microsoft Visual Studio Community 2019.
Центр Unity продолжает установку Unity в фоновом режиме. По завершении можно создать новый проект, выбрав вкладку «Проекты» и нажав кнопку «Создать«.
Проекты создаются с помощью редактора Unity, а не Visual Studio.
Это руководства по установке предназначено для Visual Studio для Mac. Если вы работаете с Visual Studio Code, см. документацию по разработке Unity с использованием VS Code.
Visual Studio для Mac Tools for Unity входит в состав установки Visual Studio для Mac. Для этого не требуется отдельных шагов установки. Вы можете проверить установку в меню разработки игр Visual Studio для Mac>Extensions>. Инструменты Visual Studio для Mac для Unity должны быть включены.
Настройка Unity для использования Visual Studio
По умолчанию в Unity уже должно быть настроено использование Visual Studio или Visual Studio для Mac в качестве редактора скриптов. Этот параметр можно подтвердить или изменить внешний редактор скриптов на определенную версию Visual Studio из редактора Unity.
В редакторе Unity выберите меню «Изменить > параметры «.
Выберите вкладку Внешние инструменты слева.
Добавление версии Visual Studio, которая не указана
Можно выбрать другие версии Visual Studio, которые не указаны в списке и установлены в пользовательском каталоге.
В редакторе Unity выберите меню«ПараметрыUnity>».
Выберите вкладку Внешние инструменты слева.
Используйте раскрывающийся список внешнего редактора скриптов, чтобы выбрать различные установки Visual Studio для Mac.
Чтобы завершить процесс настройки, закройте диалоговое окно Параметры.
Установка или обновление пакета редактора Visual Studio
В версиях Unity 2020 и более поздних версиях требуется отдельный пакет Unity для оптимальной работы с такими идентификаторами, как Visual Studio и Visual Studio для Mac. Этот пакет должен быть включен по умолчанию, но обновления выпускаются в этот пакет, на который можно установить в любое время.
Проверка обновлений
Рекомендуется обновлять Visual Studio и Visual Studio для Mac для последних исправлений ошибок, функций и поддержки Unity. Обновление Visual Studio не требует обновления версий Unity.
Выберите меню «Проверка справки>для обновлений «.
Если доступно обновление, Visual Studio Installer отображает новую версию. Щелкните Обновить.
Unity Code
Pradeep Puri Goswami
unity-code README
Create Unity classes, methods, loop, and Statement easily
Features
All the Unity code snippets you need. This extension intends to be the complete collection of Unity snippets for Visual Studio Code.
It takes advantage of latest Visual Studio Code snippets features to create the code faster for you.
MonoBehaviour
Editor
ScriptableObject
You never remember the property that goes with the ScriptableObject to create it via Unity create menu? Not a problem.
Installation
As in any Visual Studio Code Extension you have several options to install:
All the snippets
Start typing the names to create the corresponding snippets.
Some useful code snippets:
Loop, Statement etc.
If you have any suggestions, open an issue in the Github project page and I’ll add them as soon as I can :).
If you like the color theme of the previews, you can download it here: Base16 Ocean Dark Extended Theme.
Visual studio code 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.
Read on to find out how to configure Unity and your project to get the best possible experience.
[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 ( 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.
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 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.
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:
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.
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:
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.
Your omnisharp.json file should end up looking like this:
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:
You are now ready to code in Visual Studio Code, while getting the same warnings as you would when using Visual Studio!
Read on to learn more about:
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.
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.
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.
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:
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.
To turn on the use of the provided integration you will need to go to Unity Preferences and select the newly created VSCode tab.
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.
Step 3: Open the Project
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:
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.
Next Steps
Read on to learn more about:
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.
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:
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.
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 |
---|---|
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).
The Unity plug-in described above does the hard work (especially for configuring the port). However, if you want to know the typical launch.json file entry, here you go.
Change the port value to the current port number.
Использование инструментов Visual Studio для Unity
В этом разделе мы рассмотрим, как использовать возможности интеграции и повышения производительности набора средств Visual Studio для Unity, а также как использовать отладчик Visual Studio для разработки Unity.
Открытие скриптов Unity в Visual Studio
После установки Visual Studio в качестве внешнего редактора для Unity дважды щелкнув скрипт из редактора Unity, автоматически запустится или переключится на Visual Studio и откроется выбранный скрипт.
Кроме того, можно открыть Visual Studio без скрипта, открытого в редакторе исходного кода, выбрав меню «Ресурсы > » «Открыть проект C#» в Unity.
Доступ к документации по Unity
Доступ к документации по созданию скриптов Unity можно быстро получать из Visual Studio. Если набор средств Visual Studio для Unity не находит документацию по API в локальном режиме, он попытается найти ее через Интернет.
IntelliSense для сообщений API Unity
Средство автозавершения кода IntelliSense позволяет легко реализовать сообщения API Unity в скриптах MonoBehaviour и помогает в изучении API Unity. Чтобы использовать IntelliSense для сообщений Unity, сделайте следующее:
После ввода букв «ontri» отображается список предложений IntelliSense.
Выбранный элемент в списке можно изменить тремя способами:
с помощью клавиш со стрелками ВВЕРХ и ВНИЗ;
щелкая нужный элемент;
продолжив ввод имени нужного элемента.
IntelliSense может вставить выбранное сообщение Unity, включая все необходимые параметры:
при нажатии клавиши TAB;
при нажатии клавиши ВВОД;
при двойном щелчке выбранного элемента.
Мастер создания скриптов Unity MonoBehavior
Мастер MonoBehavior можно использовать для просмотра списка всех методов API Unity и быстрого выполнения пустого определения. Эта функция, особенно со включенным параметром Создать комментарии для метода, полезна при изучении того, что доступно в Unity API.
Создание определений пустых методов MonoBehavior с помощью мастера MonoBehavior.
В Visual Studio поместите курсор туда, где необходимо вставить методы, а затем нажмите клавиши CTRL+SHIFT+M для запуска мастера MonoBehavior. В Visual Studio для Mac нажмите клавиши CMD+SHIFT+M.
В окне Создание методов скрипта установите флажок рядом с именем каждого метода, который нужно добавить.
Чтобы выбрать необходимую версию, используйте раскрывающийся список Версия платформы.
Методы по умолчанию вставляются в позицию курсора. В качестве альтернативы можно вставить их после любого метода, который уже реализован в классе. Для этого измените значение раскрывающегося списка точка вставки на нужное расположение.
Если вы хотите, чтобы мастер создавал комментарии для выбранных методов, установите флажок Создать комментарии к методу. Эти комментарии позволяют лучше понять, когда вызывается метод и каковы его общие функции.
Нажмите кнопку ОК, чтобы выйти из мастера и вставить методы в код.
Обозреватель проектов Unity
Обозреватель проектов Unity показывает все файлы и каталоги ваших проектов Unity в том же виде, что и редактор Unity. Это отличается от навигации по сценариям Unity с помощью обычного обозревателя решений Visual Studio, который организует их в проекты и решения, созданные Visual Studio.
Отладка Unity
Набор средств Visual Studio для Unity позволяет отлаживать скрипты редакторов и игр для проекта Unity с помощью мощного отладчика Visual Studio.
Отладка в редакторе Unity
Начать отладку
Остановка отладки
В Visual Studio нажмите кнопку Стоп или используйте сочетание клавиш SHIFT + F5.
Нажмите кнопку Остановить в Visual Studio для Mac или клавиши SHIFT+COMMAND+ВВОД.
Дополнительные сведения об отладке в Visual Studio см. в документации по отладчику Visual Studio.
Подключение к Unity и воспроизведение
Для дополнительного удобства кнопку Подключить к Unity можно заменить на режим Подключить к Unity и воспроизвести.
Щелкните небольшую стрелку вниз рядом с кнопкой Подключить к Unity.
В раскрывшемся меню выберите Подключить к Unity и воспроизвести.
Затем на кнопке «Воспроизведение» появляется метка Подключение к Unity и воспроизведение. Нажатие этой кнопки или использование клавиши F5 приведет к автоматическому переключению на редактор Unity и запуску игры в редакторе, в дополнение к подключению отладчика Visual Studio.
Начать отладку и воспроизведение в редакторе Unity можно за один шаг, непосредственно из Visual Studio для Mac, выбрав конфигурацию Подключение к Unity и воспроизведение.
Отладка сборок проигрывателя Unity
Вы можете отлаживать сборки разработки игроков Unity с помощью Visual Studio.
Включение отладки скриптов в проигрывателе Unity
В Unity откройте параметры сборки, выбрав «Параметры сборки файлов>«.
В окне параметров сборки установите флажки Сборка разработки и Отладка скриптов.
Выбор экземпляр Unity для присоединения отладчика
В Visual Studio в главном меню выберите «Отладка Присоединения отладчика > Unity«.
В диалоговом окне Выбор экземпляра Unity отображаются сведения о каждом экземпляре Unity, к которому можно подключиться.
Проект Имя проекта Unity, который выполняется в этом экземпляре Unity.
Компьютер Имя компьютера или устройства, на котором выполняется этот экземпляр Unity.
Тип Редактор, если этот экземпляр Unity выполняется как часть редактора Unity; Проигрыватель, если этот экземпляр Unity является автономным игроком.
Порт Номер порта UDP-сокета, через который данный экземпляр Unity обменивается данными.
Так как инструменты Visual Studio для Unity и экземпляр Unity взаимодействуют по сетевому сокету UDP, брандмауэру может потребоваться правило, разрешающее его. При необходимости может появиться запрос, вам потребуется авторизовать подключение, чтобы VSTU и Unity могли обмениваться данными.
Выбор экземпляра Unity, который не отображается в списке
Если у вас есть известный проигрыватель Unity, который не отображается в списке, можно использовать кнопку «Входной IP-адрес» в окне «Выбор экземпляра Unity». Введите IP-адрес и порт работающего проигрывателя Unity, чтобы подключить отладчик.
Чтобы упростить отладку этого проигрывателя, не вводя IP-адрес и порт каждый раз, включите параметр «Использовать сохраненные целевые объекты отладки» в > меню «Средства параметров>» для Unity > «Общие«.
Visual Studio будет отображать сохраненные целевые объекты отладки в качестве параметра в кнопке «Присоединиться к Unity».
Отладка библиотеки DLL в проекте Unity
Многие разработчики Unity создают компоненты кода в виде внешних библиотек DLL, чтобы разрабатываемые ими функции можно было легко совместно использовать с другими проектами. Набор средств Visual Studio для Unity упрощает отладку кода в этих библиотеках DLL без создания проблем для другого кода в проекте Unity.
В настоящее время набор средств Visual Studio для Unity поддерживает только управляемые библиотеки DLL. Он не поддерживает отладку библиотек DLL машинного кода, например библиотек, созданных на языке C++.
Обратите внимание, что описанный здесь сценарий предполагает, что у вас есть исходный код, то есть вы разрабатываете или повторно используете свой собственный код, или у вас есть исходный код для библиотеки стороннего разработчика и вы планируете его развернуть в проекте Unity как библиотеку DLL. Данный сценарий не описывает отладку библиотеки DLL, для которой у вас нет исходного кода.
Отладка проекта с управляемой библиотекой DLL, используемой в проекте Unity
Добавьте существующий проект библиотеки DLL в решение Visual Studio, которое создается набором средств Visual Studio для Unity. В ряде случаев вы можете создать новый проект с управляемой библиотекой DLL, который будет содержать компоненты кода проекта Unity. В этом сценарии в решение Visual Studio можно добавить новый проект с управляемой библиотекой DLL.
Existing Item menu.» title=»vstu_debugging_dll_add_existing» data-linktype=»relative-path»/>
В любом случае набор средств Visual Studio для Unity сохраняет ссылку на проект, даже если он должен повторно создать файлы проекта и решения, поэтому эти действия нужно будет выполнить только один раз.
Создайте ссылку на нужный профиль платформы Unity в проекте DLL. В Visual Studio в свойствах проекта DLL для свойства Целевая платформа укажите версию платформы Unity, которую вы используете. Это библиотека базового класса Unity, соответствующая уровню совместимости API, на который ориентирован ваш проект, например библиотека базовых классов Unity full, micro или web. Благодаря этому ваша библиотека DLL не будет вызывать методы платформы, существующие на других платформах или уровнях совместимости, но которые могут отсутствовать в версии платформы Unity, которую вы используете.
Скопируйте библиотеку DLL в папку Asset (ресурсы) своего проекта Unity. В Unity ресурсы представляют собой файлы, которые упаковываются и развертываются вместе с вашим приложением Unity, чтобы их можно было загружать во время выполнения. Так как библиотеки DLL связываются во время выполнения, их необходимо развертывать как ресурсы. Для развертывания в виде ресурса редактору Unity требуется, чтобы библиотеки DLL были помещены в папку Assets вашего проекта Unity. Предусмотрены два способа выполнения этой задачи.
Измените параметры сборки проекта DLL, чтобы добавить выполняемую после сборки задачу, которая скопирует выходные файлы DLL и PDB из выходной папки в папку Активы проекта Unity.
Измените параметры сборки проекта DLL, чтобы сделать выходной папкой папку Assets проекта Unity. Теперь файлы DLL и PDB будут сразу помещаться в папку Assets.
PDB-файлы необходимы для отладки, так как они содержат символы отладки библиотеки DLL и сопоставляют код DLL с формой его исходного кода. Если будет применяться устаревшая среда выполнения, Инструменты Visual Studio для Unity будут использовать сведения из файлов DLL и PDB для создания файла DLL.MDB. Это формат отладочных символов, применяемый устаревшим модулем обработки скрипов Unity. Если будет применяться новая среда выполнения и формат Portable-PDB, Инструменты Visual Studio для Unity не будут пытаться преобразовывать символы, так как новая среда выполнения Unity может самостоятельно обрабатывать файлы Portable-PDB.
См. подробнее сведения о создании PDB-файлов. Если будет применяться новая среда выполнения, убедитесь, что для параметра «Отладочная информация» задано значение «Переносимый» для корректного создания файла Portable PDB. Если будет применяться устаревшая среда выполнения, воспользуйтесь значением «Полный».
Выполните отладку своего кода. Теперь вы можете отлаживать свой исходный код DLL вместе с исходным кодом проекта Unity и использовать все доступные функции, например точки останова и пошаговое выполнение кода.
Сочетания клавиш
Для быстрого доступа средств Unity к функциям Visual Studio можно использовать соответствующие сочетания клавиш. Ниже приведен список таких сочетаний клавиш.
Команда | Сочетание клавиш | Имя контекстной команды |
---|---|---|
Открыть мастер MonoBehavior | CTRL+SHIFT+M | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Открыть обозреватель проектов Unity | ALT+SHIFT+E | View.UnityProjectExplorer |
Доступ к документации по Unity | CTRL+ALT+M, CTRL+H | Help.UnityAPIReference |
Присоединиться к отладчику Unity (проигрыватель или редактор) | значение по умолчанию отсутствует | Debug.AttachUnityDebugger |
Если вас не устраивает сочетание клавиш по умолчанию, его можно изменить. Чтобы узнать, как это сделать, см. статью Определение и настройка сочетаний клавиш в Visual Studio.
Команда | Сочетание клавиш | Имя контекстной команды |
---|---|---|
Открыть мастер MonoBehavior | Cmd+Shift+М | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Доступ к документации по Unity | Cmd+’ | Help.UnityAPIReference |
Если вас не устраивает сочетание клавиш по умолчанию, его можно изменить. Сведения о том, как изменить его, см. в разделе «Настройка интегрированной среды разработки».
Integrated development environment (IDE) support
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 (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:
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:
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.
Integrated development environment (IDE) support
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 (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:
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:
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.
Integrated development environment (IDE) support
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 (default IDE on Windows and macOS)
Visual Studio is installed by default when you install Unity on Windows and macOS. On Windows, you can choose to exclude it when you select which components to download and install. Visual Studio is set as the External Script Editor in Preferences (menu: Unity > Preferences > External Tools > External Script Editor). With this option enabled, Unity launches Visual Studio and uses it as the default editor for all script files.
On macOS, Unity includes 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:
On Windows, Unity also includes Visual Studio 2017 Community.
Visual Studio Code (Windows, macOS, Linux)
Unity supports opening scripts in Visual Studio Code (VS Code). To open scripts in VS Code, select it as the External Script Editor in the Editor Preferences (menu: Unity > Preferences > External Tools > External Script Editor). 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:
JetBrains Rider (Windows, macOS, Linux)
Unity supports opening scripts in JetBrains Rider. To open scripts in Rider, select it as the External Script Editor in the Editor Preferences (menu: Unity > Preferences > External Tools > External Script Editor).
Integrated development environment (IDE) support
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 (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:
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:
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.
Integrated development environment (IDE) support
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 (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:
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:
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.
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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 Bar
Unity’s Code Optimization setting has two modes:
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.
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.
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:
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:
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.
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.
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
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
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.
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
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.
Visual Studio C# integration
Unity integrates with Microsoft Visual Studio through the Code Editor Package for Visual Studio. This package is pre-installed when you install Unity. If Visual Studio is installed at the time you install Unity, then Unity uses Visual Studio to open and edit scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary by default.
The Visual Studio Editor in the Package Manager Window
Set Visual Studio as your default script editor
Unity automatically uses Visual Studio as its default script editor if Visual Studio is installed when you install Unity, or if you install Visual Studio as part of the Unity installation process. You can install Visual Studio as a module into an existing Unity installation. For more information, see Downloading and installing Editors and modules with the Unity Hub.
To set your default script editor manually:
A: The External Script Editor dropdown menu, which displays the name and version of the selected script editor.
B: The name and version of the Unity package that integrates with the selected script editor.
Unity uses Visual Studio’s C# compiler to compile scripts. When you use the Visual Studio Editor package with Visual Studio, both Unity and Visual Studio display details of any errors in your scripts.
Quickstart: Configure Visual Studio for cross-platform development with Unity
In this quickstart, you learn how to install the Visual Studio Tools for Unity extension and configure it for developing cross-platform games and apps with Unity. The Visual Studio Tools for Unity extension is free and provides support for writing and debugging C# and more. Visit the Tools for Unity overview for a complete list of what that workload includes.
Install Visual Studio and Unity
Select Install, or Modify if Visual Studio is already installed.
Select the Workloads tab, then select the Game development with Unity workload.
If Unity isn’t already installed, select Unity Hub under Optional.
Select Modify or Install to complete the installation.
When Visual Studio completes the installation process, you’re ready to set up Unity.
Open the Unity Hub, which was installed during the Visual Studio Tools for Unity installation.
On the left of the Unity Hub window, select the Installs tab.
Select the Add button.
In the Add Unity Version window, select a version of Unity to install.
Select Next to continue the installation.
In the Add modules to your install step, select Done.
If you’ve already installed Visual Studio 2022, you can deselect the Microsoft Visual Studio Community 2019 option.
The Unity Hub continues installing Unity in the background. When it’s complete, you can create a new project by selecting the Projects tab and selecting New.
Projects are created using the Unity Editor and not Visual Studio.
This installation guide is for Visual Studio for Mac. If you’re using Visual Studio Code, please visit the Unity Development with VS Code documentation.
Visual Studio for Mac Tools for Unity is included with the installation of Visual Studio for Mac. It requires no separate installation steps. You can verify the installation in the Visual Studio for Mac > Extensions > Game Development menu. Visual Studio for Mac Tools for Unity should be enabled.
Configure Unity to use Visual Studio
By default, Unity should already be configured to use Visual Studio or Visual Studio for Mac as a script editor. You can confirm this option or change the external script editor to a specific version of Visual Studio from the Unity Editor.
In the Unity Editor, select the Edit > Preferences menu.
On the left, select the External Tools tab.
Add a version of Visual Studio that isn’t listed
It’s possible to select other versions of Visual Studio that are unlisted and installed in a custom directory.
In the Unity Editor, select the Unity > Preferences menu.
On the left, select the External Tools tab.
Use the External Script Editor dropdown list to choose different installations of Visual Studio for Mac.
Close the Preferences dialog to complete the configuration process.
Install or update the Visual Studio Editor package
In Unity versions 2020 and later, a separate Unity Package is required for the best experience working with IDEs like Visual Studio and Visual Studio for Mac. This package should be included by default, but updates are released to this package that you can install to at any time.
Check for updates
We recommend that you keep Visual Studio and Visual Studio for Mac updated for the latest bug fixes, features, and Unity support. Updating Visual Studio doesn’t require an update of Unity versions.
Select the Help > Check for Updates menu.
If an update is available, the Visual Studio Installer shows a new version. Select Update.
Debugger for Unity
Unity Technologies
Unity Debugger Extension for Visual Studio Code
This extension is not officially supported by Unity Technologies.
Use Visual Studio Code to debug your Unity C# projects.
Setup
Open your Unity project folder in the Visual Studio Code.
Select the debug view on the left and click the cogwheel.
Attach to Process Picker
New in version 1.1.0 it is now possible to select which Unity process you want to attach to from a quick pick menu.
In the command palette type «Unity Attach Debugger»
Wait a bit for the Unity processes list to appear at the top of the VS Code window.
Select the Unity process you wish to attach the debugger to.
Usage
Strings in the variable view is truncated to 100 characters, with appended ellipsis. «Example wor. «. To view the entire value of this string add it to the watch fields. In addition, evaluating the variable using the debugger console will reveal the same result.
Building
To build this repository, clone it then get all submodules:
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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 Bar
Unity’s Code Optimization setting has two modes:
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.
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.
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:
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:
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.
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.
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
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 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
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.
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
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.
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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. 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.
To change which mode the Unity Editor starts up in, go to Edit (macOS: Unity) > Preferences > General > Code Optimization On Startup.
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:
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:
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.
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.
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
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
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.
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
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.
Use Visual Studio Tools for Unity
In this section, you’ll learn how to use Visual Studio Tools for Unity’s integration and productivity features, and how to use the Visual Studio debugger for Unity development.
Open Unity scripts in Visual Studio
Once Visual Studio is set as the external editor for Unity, double-clicking a script from the Unity editor will automatically launch or switch to Visual Studio and open the chosen script.
Alternatively, you can open Visual Studio with no script open in the source editor by selecting the Assets > Open C# Project menu in Unity.
Unity documentation access
You can access the Unity scripting documentation quickly from Visual Studio. If Visual Studio Tools for Unity doesn’t find the API documentation locally, it will try to find it online.
Intellisense for Unity API Messages
Intellisense code-completion makes it easy to implement Unity API messages in MonoBehaviour scripts, and assists with learning the Unity API. To use IntelliSense for Unity messages:
Once the letters «ontri» have been typed, a list of IntelliSense suggestions appears.
The selection on the list can be changed in three ways:
With the Up and Down arrow keys.
By clicking with the mouse on the desired item.
By continuing to type the name of the desired item.
IntelliSense can insert the selected Unity message, including any necessary parameters:
By pressing Tab.
By pressing Enter.
By double-clicking the selected item.
Unity MonoBehavior scripting wizard
You can use the MonoBehavior wizard to view a list of all the Unity API methods and quickly implement an empty definition. This feature, particularly with the Generate method comments option enabled, is helpful if you are still learning what’s available in the Unity API.
To create empty MonoBehavior method definitions with the MonoBehavior wizard:
In Visual Studio, position the cursor where you want the methods to be inserted, then press Ctrl+Shift+M to launch the MonoBehavior wizard. In Visual Studio for Mac, press Cmd+Shift+M.
In the Create script methods window, mark the checkbox next to the name of each method you want to add.
Use the Framework version dropdown to select your desired version.
By default, the methods are inserted at the position of the cursor. Alternatively, you can choose to insert them after any method that’s already implemented in your class by changing the value of the Insertion point dropdown to the location you want.
If you want the wizard to generate comments for the methods you selected, mark the Generate method comments checkbox. These comments are meant to help you understand when the method is called and what its general responsibilities are.
Choose the OK button to exit the wizard and insert the methods into your code.
Unity Project Explorer
The Unity Project Explorer shows all of your Unity project files and directories in the same way that the Unity Editor does. This is different than navigating your Unity scripts with the normal Visual Studio Solution Explorer, which organizes them into projects and a solution generated by Visual Studio.
Unity debugging
Visual Studio Tools for Unity lets you debug both editor and game scripts for your Unity project using Visual Studio’s powerful debugger.
Debug in the Unity editor
Start debugging
Stop debugging
Click the Stop button in Visual Studio, or use the keyboard shortcut Shift + F5.
Click the Stop button in Visual Studio for Mac, or press Shift + Command + Return.
Attach to Unity and Play
For added convenience, you can change the Attach to Unity button to Attach to Unity and Play mode.
Click the small down arrow next to the Attach to Unity button.
Select Attach to Unity and Play from the dropdown menu.
The play button becomes labeled Attach to Unity and Play. Clicking this button or using the keyboard shortcut F5 now automatically switches to the Unity editor and runs the game in the editor, in addition to attaching the Visual Studio debugger.
Starting debugging and playing the Unity editor can be completed in a single step directly from Visual Studio for Mac by choosing the Attach to Unity and Play configuration.
If you started debugging using the Attach to Unity and Play configuration, the Stop button will also stop the Unity Editor.
Debug Unity player builds
You can debug development builds of Unity players with Visual Studio.
Enable script debugging in a Unity player
In Unity, open the Build Settings by selecting File > Build Settings.
In the Build Settings window, mark the Development Build and Script Debugging checkboxes.
Select a Unity instance to attach the debugger to
In Visual Studio, on the main menu, choose Debug > Attach Unity Debugger.
The Select Unity Instance dialog displays some information about each Unity instance that you can connect to.
Project The name of the Unity project that’s running in this instance of Unity.
Machine The name of the computer or device that this instance of Unity is running on.
Type Editor if this instance of Unity is running as part of the Unity Editor; Player if this instance of Unity is a stand-alone player.
Port The port number of the UDP socket that this instance of Unity is communicating over.
Because Visual Studio Tools for Unity and the Unity instance are communicating over a UDP network socket, your firewall may need rule to allow it. If needed, you may see a prompt, you’ll have to authorize the connection so that VSTU and Unity can communicate.
Selecting a Unity instance that doesn’t appear in the list
If you have a known Unity Player running that doesn’t appear in the list, you can use the Input IP button on the Select Unity Instance window. Enter the IP address and port of the running Unity Player to connect the debugger.
To make it easier for you to continue debugging that player without entering the IP and port each time, enable the Use saved debug targets setting in the Tools > Options > Tools for Unity > General menu.
Visual Studio will show saved debug targets as an option in Attach to Unity button.
Debug a DLL in your Unity project
Many Unity developers are writing code components as external DLLs so that the functionality they develop can be easily shared with other projects. Visual Studio Tools for Unity makes it easy to debug code in these DLLs seamlessly with other code in your Unity project.
At this time, Visual Studio Tools for Unity only supports managed DLLs. It does not support debugging of native code DLLs, such as those written in C++.
Note that the scenario described here assumes that you have the source code—that is, you are developing or re-using your own first-party code, or you have the source code to a third-party library, and plan to deploy it in your Unity project as a DLL. This scenario does not describe debugging a DLL for which you do not have the source code.
To debug a managed DLL project used in your Unity project
Add your existing DLL project to the Visual Studio solution generated by Visual Studio Tools for Unity. Less commonly, you might be starting a new managed DLL project to contain code components in your Unity project; if that’s the case, you can add a new managed DLL project to the Visual Studio solution instead.
Existing Item menu.» title=»vstu_debugging_dll_add_existing» data-linktype=»relative-path»/>
In either case, Visual Studio Tools for Unity maintains the project reference, even if it has to regenerate the project and solution files again, so you only need to perform these steps once.
Reference the correct Unity framework profile in the DLL project. In Visual Studio, in the DLL project’s properties, set the Target framework property to the Unity framework version you’re using. This is the Unity Base Class Library that matches the API compatibility that your project targets, such as the Unity full, micro, or web base class libraries. This prevents your DLL from calling framework methods that exist in other frameworks or compatibility levels, but which might not exist in the Unity framework version you’re using.
Copy the DLL to your Unity project’s Asset folder. In Unity, assets are files that are packaged and deployed together with your Unity app so that they can be loaded at run-time. Since DLLs are linked at run time, DLLs must be deployed as assets. To be deployed as an asset, the Unity Editor requires the DLLs to be put inside the Assets folder in your Unity project. There are two ways you can do this:
Modify the build settings of your DLL project to include a post-built task that copies the output DLL and PDB files from its output folder to the Assets folder of your Unity project.
Modify the build settings of your DLL project to set its output folder to be the Assets folder of your Unity project. Both DLL and PDB files will be placed in the Assets folder.
The PDB files are needed for debugging because they contain the DLL’s debugging symbols, and map the DLL code to its source code form. If you are targeting the legacy runtime, Visual Studio Tools for Unity will use information from the DLL and PDB to create a DLL.MDB file, which is the debug symbol format used by the legacy Unity scripting engine. If you are targeting the new runtime, and using Portable-PDB, Visual Studio Tools for Unity will not try to do any symbol conversion as the new Unity runtime is able to natively consume Portable-PDBs.
More information about PDB generation can be found here. If you are targeting the new runtime, please make sure that «Debugging Information» is set to «Portable», in order to properly generate Portable-PDB. If you are targeting the legacy runtime, you need to use «Full».
Debug your code. You can now debug your DLL source code together with your Unity project’s source code, and use all the debugging features you are used to, such as breakpoints and stepping through code.
Keyboard shortcuts
You can quickly access the Unity Tools for Visual Studio functionality by using their keyboard shortcuts. Here’s a summary of the shortcuts that are available.
Command | Shortcut | Shortcut command name |
---|---|---|
Open the MonoBehavior Wizard | Ctrl+Shift+M | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Open the Unity Project Explorer | Alt+Shift+E | View.UnityProjectExplorer |
Access Unity documentation | Ctrl+Alt+M, Ctrl+H | Help.UnityAPIReference |
Attach to Unity debugger (player or editor) | no default | Debug.AttachUnityDebugger |
You can change the shortcut key combinations if you don’t like the default. For information on how to change it, see Identify and customize keyboard shortcuts in Visual Studio.
Command | Shortcut | Shortcut command name |
---|---|---|
Open the MonoBehavior Wizard | Cmd+Shift+M | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Access Unity documentation | Cmd+’ | Help.UnityAPIReference |
You can change the shortcut key combinations if you don’t like the default. For information on how to change it, see Customizing the IDE.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Не смотря на то, что Visual Studio поставляется со своим собственным компилятором C#, и вы можете использовать его для проверки ваших скриптов на ошибки, Unity по прежнему использует собственный компилятор C# для компиляции ваших скриптов. Однако использование компилятора Visual Studio все равно очень эффективно, потому что вам не нужно постоянно переключаться в Unity чтобы проверить свои скрипты на наличие ошибок.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Не смотря на то, что Visual Studio поставляется со своим собственным компилятором C#, и вы можете использовать его для проверки ваших скриптов на ошибки, Unity по прежнему использует собственный компилятор C# для компиляции ваших скриптов. Однако использование компилятора Visual Studio все равно очень эффективно, потому что вам не нужно постоянно переключаться в Unity чтобы проверить свои скрипты на наличие ошибок.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Краткое руководство. Настройка Visual Studio для кроссплатформенной разработки с использованием Unity
Для Visual Studio Code & Unity ознакомьтесь с документацией по разработке Unity с VS Code.
Установка Visual Studio и Unity
Загрузите установщик Visual Studio или запустите его (если он был ранее установлен).
Выберите «Установить» или «Изменить«, если Visual Studio уже установлен.
На вкладке Рабочие нагрузки выберите рабочую нагрузку Разработка игр с помощью Unity.
Если Unity еще не установлен, выберите Unity Hub в разделе «Необязательно«.
Щелкните Изменить или Установить, чтобы завершить установку.
Когда Visual Studio завершит процесс установки, вы можете настроить Unity.
Откройте программу Unity Hub, которая была установлена во время установки Инструментов Visual Studio для Unity.
В левой части окна Unity Hub откройте вкладку Установки.
Нажмите кнопку Добавить.
В окне «Добавление версии Unity » выберите версию Unity для установки.
Нажмите кнопку Далее, чтобы продолжить установку.
На шаге Добавление модулей к установке выберите Готово.
Если вы уже установили Visual Studio 2022, можно отменить выбор параметра Microsoft Visual Studio Community 2019.
Центр Unity продолжает установку Unity в фоновом режиме. По завершении можно создать новый проект, выбрав вкладку «Проекты» и нажав кнопку «Создать«.
Проекты создаются с помощью редактора Unity, а не Visual Studio.
Это руководства по установке предназначено для Visual Studio для Mac. Если вы работаете с Visual Studio Code, см. документацию по разработке Unity с использованием VS Code.
Visual Studio для Mac Tools for Unity входит в состав установки Visual Studio для Mac. Для этого не требуется отдельных шагов установки. Вы можете проверить установку в меню разработки игр Visual Studio для Mac>Extensions>. Инструменты Visual Studio для Mac для Unity должны быть включены.
Настройка Unity для использования Visual Studio
По умолчанию в Unity уже должно быть настроено использование Visual Studio или Visual Studio для Mac в качестве редактора скриптов. Этот параметр можно подтвердить или изменить внешний редактор скриптов на определенную версию Visual Studio из редактора Unity.
В редакторе Unity выберите меню «Изменить > параметры «.
Выберите вкладку Внешние инструменты слева.
Добавление версии Visual Studio, которая не указана
Можно выбрать другие версии Visual Studio, которые не указаны в списке и установлены в пользовательском каталоге.
В редакторе Unity выберите меню«ПараметрыUnity>».
Выберите вкладку Внешние инструменты слева.
Используйте раскрывающийся список внешнего редактора скриптов, чтобы выбрать различные установки Visual Studio для Mac.
Чтобы завершить процесс настройки, закройте диалоговое окно Параметры.
Установка или обновление пакета редактора Visual Studio
В версиях Unity 2020 и более поздних версиях требуется отдельный пакет Unity для оптимальной работы с такими идентификаторами, как Visual Studio и Visual Studio для Mac. Этот пакет должен быть включен по умолчанию, но обновления выпускаются в этот пакет, на который можно установить в любое время.
Проверка обновлений
Рекомендуется обновлять Visual Studio и Visual Studio для Mac для последних исправлений ошибок, функций и поддержки Unity. Обновление Visual Studio не требует обновления версий Unity.
Выберите меню «Проверка справки>для обновлений «.
Если доступно обновление, Visual Studio Installer отображает новую версию. Щелкните Обновить.
Unity Tools
Tobiah Zarlez
Unity Tools for Visual Studio Code
What this extension is
This is an unofficial extension created by Tobiah Zarlez, and is not affiliated in any way with Unity Technologies.
The goal of this extension is to add miscellaneous functionality to Visual Studio Code for Unity developers.
This extension also acts as an extension package for another Unity related VSCode extension. Specifically, «Unity.unity-debug»
What this extension isn’t
This is not a comprehensive set of tools for Unity development, nor does it provide any debugging features.
If you want to debug your Unity projects, I would recommend getting Unity’s official debugger for Visual Studio Code.
Can you add XZY feature?
Possibly! Let me know, I’d love to hear your suggestions on what tools you’d like to see added to this collection.
How to install
You can install this extension directly from the Visual Studio Marketplace.
Launch VS Code Quick Open (Ctrl+P) and copy/paste the following command:
Feature list
Command: Open Documentation for Selection
Use the pallet command «Unity Tools: Open Documentation for Selection» ( Cmd+’ on OSX or Ctrl+’ on Windows and Linux) to open the Unity Documentation for the currently selected class.
Command: Search Documentation
Use the pallet command «Unity Tools: Search Documentation» (Shortcut: Cmd+Shift+’ on OSX or Ctrl+Shift+’ on Windows and Linux) where you can quickly enter whatever you want to search for.
Command: Search MSFT Documentation
Use the pallet command «Unity Tools: Search MSFT Documentation» where you can enter whatever you want to search the MSFT documentation for.
Command: Open VSCode Documentation
Added the pallet command «Unity Tools: Open VSCode Documentation» to open the Unity Development with VS Code page on the Visual Studio Code Documentation.
Command: Generate Organizational Folders
Added the pallet command «Unity Tools: Generate Organizational Folders» to create some default organizational folders to your project’s Assets Folder. The list of default folders are below:
Configuration
You can also set which Unity version should be used when accessing online documentation. Make sure the version number you enter is valid for Unity’s documentation.
You can also enable/disable the «Open Documentation» option in right-click menu by the below setting. Default value is true.
If you rather search local documentation rather than online, set a value to unity-tools.localDocumentationPath.
If you do not set localDocumentationViewer, localDocumentationPath will not work. This may or may not be true on Mac or Linux, I have not had the opportunity to test it! If you have, please let me know.
dotBunny/VSCode
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Unity > 4.5 && Unity
Visual Studio Code 0.10.1+
Get the latest version, or have a look at the past releases of the VSCode plugin for support for your version.
A good number of people have needed to install Mono in order for many of the issues with OmniSharp to be resolved. I would suggest installing the latest package available at the Mono Project. Don’t worry it will not mess with Unity.
Unity Asset Store Package
A UAS packaged version of the plugin is available for your consumption.
Once the VSCode file is in place, simply navigate your way to the Unity Preferences and select VSCode and check the Enable Integration option.
That’s it! You’re ready to go!
OK, so maybe some people need a little video explaining some of the finer details of how to use the plugin. So I shot a quick video that highlights the ups and the downs (like Unity hanging after debugging sometimes) for people to watch. Please note this video is from a previous version of the plugin where things are in the menu, this has changed since then.
I use the plugin every day on a Mac (so it’s battle tested there), and occasionally test it on a Windows VM. As for the recently announced Linux support, it should work just like the Mac version. I’ll get around to installing the Linux editor sometime in the near future.
The Windows version of Visual Studio Code currently does not support debugging Mono, and will just throw a warning if you try to do it. The «Code» team is aware of this limitation, and we’ll leave it at that.
With version 2.0 of the plugin, I’ve introduced a feature where it will auto-update itself if allowed. This should make things a lot easier in the future.
Please provide feedback through the GitHub Issue system.
Набор средств Visual Studio для Unity
Обзор
Инструменты Visual Studio для Unity содержат обширный набор функций, повышающих эффективность написания и отладки скриптов C# для Unity и работы с проектами Unity.
Доступно для Windows и macOS
Инструменты Visual Studio для Unity являются бесплатными и поддерживают Visual Studio 2017 Community, Professional, Enterprise и более поздние версии. Рекомендуется скачать и использовать последнюю версию Visual Studio.
Инструменты Visual Studio для Unity являются бесплатными и включены в каждую установку Visual Studio для Mac 2017 и более поздних версий. Рекомендуется скачать и использовать последнюю версию Visual Studio для Mac.
Дополнительные сведения об установке и настройке см. в средствах Visual Studio для Unity для Unity.
Поддерживаемые версии Unity
Пакет Unity редактора Visual Studio
Для Unity 2020.1 и более поздних версий требуется пакет Unity для внешних инструментов редактора, таких как Visual Studio и Visual Studio для Mac. Документация для получения дополнительных сведений об этих изменениях в записи блога по Unity.
В разделе о начале работы содержатся дополнительные сведения о конфигурации пакета редактора Visual Studio.
Рекомендуется использовать последнюю версию пакета редактора Visual Studio.
Visual Studio | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Недоступно |
Visual Studio для Mac | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Н/Д |
Компоненты
Функции событий Unity
Создавайте код для нескольких функций событий Unity и их комментариев с помощью ⌘+Shift+M.
Быстро исправьте ошибки параметров в функциях событий, которые были добавлены вручную, с помощью предложений по быстрому исправлению.
Высокопроизводительный отладчик
Инструменты Visual Studio для Unity поддерживают надежные функции отладки, характерные для Visual Studio:
Быстрые исправления и предложения по рефакторингу
Напишите эффективный код, сочетающий в себе лучшие методики и глубокое понимание проектов Unity Visual Studio.
Указания CodeLens
Определяйте места, откуда вызывается код, используя указания CodeLens, которые показывают неявные вызовы из ресурсов Unity. Выберите указание, чтобы просмотреть список неявных вызовов. При выборе конкретного вызова выполняется переход непосредственно к объекту в редакторе Unity.
Быстро отличайте код от методов Unity с помощью указаний для каждой функции события Unity.
Обозреватель проектов Unity
Отображайте файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Представление проекта Unity
Visual Studio для Mac автоматически отображает файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Документация по Unity
Просматривайте документацию по Unity непосредственно во всплывающих подсказках при проверке кода.
Чтобы быстро найти документацию по Unity, выделите имя класса или метода, а затем выберите пункт меню » > Справка по API Unity».
Поддержка шейдеров
Выделение синтаксиса и автоматическое завершение для файлов шейдера.
Поддержка файлов определения сборки
Редактируйте файлы определения сборки Unity (.asmdef) непосредственно в Visual Studio с помощью раскраски и завершения ключевых слов.
Выполнение и отладка модульных тестов
Создавайте, выполняйте и отлаживайте модульные тесты непосредственно в Visual Studio для Mac.
Автоматическое обновление ресурсов Unity
Тратить меньше времени на переключение между Unity и Visual Studio. Изменения кода автоматически обновляются в Unity при сохранении файлов.
Набор средств Visual Studio для Unity
Обзор
Инструменты Visual Studio для Unity содержат обширный набор функций, повышающих эффективность написания и отладки скриптов C# для Unity и работы с проектами Unity.
Доступно для Windows и macOS
Инструменты Visual Studio для Unity являются бесплатными и поддерживают Visual Studio 2017 Community, Professional, Enterprise и более поздние версии. Рекомендуется скачать и использовать последнюю версию Visual Studio.
Инструменты Visual Studio для Unity являются бесплатными и включены в каждую установку Visual Studio для Mac 2017 и более поздних версий. Рекомендуется скачать и использовать последнюю версию Visual Studio для Mac.
Дополнительные сведения об установке и настройке см. в средствах Visual Studio для Unity для Unity.
Поддерживаемые версии Unity
Пакет Unity редактора Visual Studio
Для Unity 2020.1 и более поздних версий требуется пакет Unity для внешних инструментов редактора, таких как Visual Studio и Visual Studio для Mac. Документация для получения дополнительных сведений об этих изменениях в записи блога по Unity.
В разделе о начале работы содержатся дополнительные сведения о конфигурации пакета редактора Visual Studio.
Рекомендуется использовать последнюю версию пакета редактора Visual Studio.
Visual Studio | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Недоступно |
Visual Studio для Mac | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Н/Д |
Компоненты
Функции событий Unity
Создавайте код для нескольких функций событий Unity и их комментариев с помощью ⌘+Shift+M.
Быстро исправьте ошибки параметров в функциях событий, которые были добавлены вручную, с помощью предложений по быстрому исправлению.
Высокопроизводительный отладчик
Инструменты Visual Studio для Unity поддерживают надежные функции отладки, характерные для Visual Studio:
Быстрые исправления и предложения по рефакторингу
Напишите эффективный код, сочетающий в себе лучшие методики и глубокое понимание проектов Unity Visual Studio.
Указания CodeLens
Определяйте места, откуда вызывается код, используя указания CodeLens, которые показывают неявные вызовы из ресурсов Unity. Выберите указание, чтобы просмотреть список неявных вызовов. При выборе конкретного вызова выполняется переход непосредственно к объекту в редакторе Unity.
Быстро отличайте код от методов Unity с помощью указаний для каждой функции события Unity.
Обозреватель проектов Unity
Отображайте файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Представление проекта Unity
Visual Studio для Mac автоматически отображает файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Документация по Unity
Просматривайте документацию по Unity непосредственно во всплывающих подсказках при проверке кода.
Чтобы быстро найти документацию по Unity, выделите имя класса или метода, а затем выберите пункт меню » > Справка по API Unity».
Поддержка шейдеров
Выделение синтаксиса и автоматическое завершение для файлов шейдера.
Поддержка файлов определения сборки
Редактируйте файлы определения сборки Unity (.asmdef) непосредственно в Visual Studio с помощью раскраски и завершения ключевых слов.
Выполнение и отладка модульных тестов
Создавайте, выполняйте и отлаживайте модульные тесты непосредственно в Visual Studio для Mac.
Автоматическое обновление ресурсов Unity
Тратить меньше времени на переключение между Unity и Visual Studio. Изменения кода автоматически обновляются в Unity при сохранении файлов.
Использование инструментов Visual Studio для Unity
В этом разделе мы рассмотрим, как использовать возможности интеграции и повышения производительности набора средств Visual Studio для Unity, а также как использовать отладчик Visual Studio для разработки Unity.
Открытие скриптов Unity в Visual Studio
После установки Visual Studio в качестве внешнего редактора для Unity дважды щелкнув скрипт из редактора Unity, автоматически запустится или переключится на Visual Studio и откроется выбранный скрипт.
Кроме того, можно открыть Visual Studio без скрипта, открытого в редакторе исходного кода, выбрав меню «Ресурсы > » «Открыть проект C#» в Unity.
Доступ к документации по Unity
Доступ к документации по созданию скриптов Unity можно быстро получать из Visual Studio. Если набор средств Visual Studio для Unity не находит документацию по API в локальном режиме, он попытается найти ее через Интернет.
IntelliSense для сообщений API Unity
Средство автозавершения кода IntelliSense позволяет легко реализовать сообщения API Unity в скриптах MonoBehaviour и помогает в изучении API Unity. Чтобы использовать IntelliSense для сообщений Unity, сделайте следующее:
После ввода букв «ontri» отображается список предложений IntelliSense.
Выбранный элемент в списке можно изменить тремя способами:
с помощью клавиш со стрелками ВВЕРХ и ВНИЗ;
щелкая нужный элемент;
продолжив ввод имени нужного элемента.
IntelliSense может вставить выбранное сообщение Unity, включая все необходимые параметры:
при нажатии клавиши TAB;
при нажатии клавиши ВВОД;
при двойном щелчке выбранного элемента.
Мастер создания скриптов Unity MonoBehavior
Мастер MonoBehavior можно использовать для просмотра списка всех методов API Unity и быстрого выполнения пустого определения. Эта функция, особенно со включенным параметром Создать комментарии для метода, полезна при изучении того, что доступно в Unity API.
Создание определений пустых методов MonoBehavior с помощью мастера MonoBehavior.
В Visual Studio поместите курсор туда, где необходимо вставить методы, а затем нажмите клавиши CTRL+SHIFT+M для запуска мастера MonoBehavior. В Visual Studio для Mac нажмите клавиши CMD+SHIFT+M.
В окне Создание методов скрипта установите флажок рядом с именем каждого метода, который нужно добавить.
Чтобы выбрать необходимую версию, используйте раскрывающийся список Версия платформы.
Методы по умолчанию вставляются в позицию курсора. В качестве альтернативы можно вставить их после любого метода, который уже реализован в классе. Для этого измените значение раскрывающегося списка точка вставки на нужное расположение.
Если вы хотите, чтобы мастер создавал комментарии для выбранных методов, установите флажок Создать комментарии к методу. Эти комментарии позволяют лучше понять, когда вызывается метод и каковы его общие функции.
Нажмите кнопку ОК, чтобы выйти из мастера и вставить методы в код.
Обозреватель проектов Unity
Обозреватель проектов Unity показывает все файлы и каталоги ваших проектов Unity в том же виде, что и редактор Unity. Это отличается от навигации по сценариям Unity с помощью обычного обозревателя решений Visual Studio, который организует их в проекты и решения, созданные Visual Studio.
Отладка Unity
Набор средств Visual Studio для Unity позволяет отлаживать скрипты редакторов и игр для проекта Unity с помощью мощного отладчика Visual Studio.
Отладка в редакторе Unity
Начать отладку
Остановка отладки
В Visual Studio нажмите кнопку Стоп или используйте сочетание клавиш SHIFT + F5.
Нажмите кнопку Остановить в Visual Studio для Mac или клавиши SHIFT+COMMAND+ВВОД.
Дополнительные сведения об отладке в Visual Studio см. в документации по отладчику Visual Studio.
Подключение к Unity и воспроизведение
Для дополнительного удобства кнопку Подключить к Unity можно заменить на режим Подключить к Unity и воспроизвести.
Щелкните небольшую стрелку вниз рядом с кнопкой Подключить к Unity.
В раскрывшемся меню выберите Подключить к Unity и воспроизвести.
Затем на кнопке «Воспроизведение» появляется метка Подключение к Unity и воспроизведение. Нажатие этой кнопки или использование клавиши F5 приведет к автоматическому переключению на редактор Unity и запуску игры в редакторе, в дополнение к подключению отладчика Visual Studio.
Начать отладку и воспроизведение в редакторе Unity можно за один шаг, непосредственно из Visual Studio для Mac, выбрав конфигурацию Подключение к Unity и воспроизведение.
Отладка сборок проигрывателя Unity
Вы можете отлаживать сборки разработки игроков Unity с помощью Visual Studio.
Включение отладки скриптов в проигрывателе Unity
В Unity откройте параметры сборки, выбрав «Параметры сборки файлов>«.
В окне параметров сборки установите флажки Сборка разработки и Отладка скриптов.
Выбор экземпляр Unity для присоединения отладчика
В Visual Studio в главном меню выберите «Отладка Присоединения отладчика > Unity«.
В диалоговом окне Выбор экземпляра Unity отображаются сведения о каждом экземпляре Unity, к которому можно подключиться.
Проект Имя проекта Unity, который выполняется в этом экземпляре Unity.
Компьютер Имя компьютера или устройства, на котором выполняется этот экземпляр Unity.
Тип Редактор, если этот экземпляр Unity выполняется как часть редактора Unity; Проигрыватель, если этот экземпляр Unity является автономным игроком.
Порт Номер порта UDP-сокета, через который данный экземпляр Unity обменивается данными.
Так как инструменты Visual Studio для Unity и экземпляр Unity взаимодействуют по сетевому сокету UDP, брандмауэру может потребоваться правило, разрешающее его. При необходимости может появиться запрос, вам потребуется авторизовать подключение, чтобы VSTU и Unity могли обмениваться данными.
Выбор экземпляра Unity, который не отображается в списке
Если у вас есть известный проигрыватель Unity, который не отображается в списке, можно использовать кнопку «Входной IP-адрес» в окне «Выбор экземпляра Unity». Введите IP-адрес и порт работающего проигрывателя Unity, чтобы подключить отладчик.
Чтобы упростить отладку этого проигрывателя, не вводя IP-адрес и порт каждый раз, включите параметр «Использовать сохраненные целевые объекты отладки» в > меню «Средства параметров>» для Unity > «Общие«.
Visual Studio будет отображать сохраненные целевые объекты отладки в качестве параметра в кнопке «Присоединиться к Unity».
Отладка библиотеки DLL в проекте Unity
Многие разработчики Unity создают компоненты кода в виде внешних библиотек DLL, чтобы разрабатываемые ими функции можно было легко совместно использовать с другими проектами. Набор средств Visual Studio для Unity упрощает отладку кода в этих библиотеках DLL без создания проблем для другого кода в проекте Unity.
В настоящее время набор средств Visual Studio для Unity поддерживает только управляемые библиотеки DLL. Он не поддерживает отладку библиотек DLL машинного кода, например библиотек, созданных на языке C++.
Обратите внимание, что описанный здесь сценарий предполагает, что у вас есть исходный код, то есть вы разрабатываете или повторно используете свой собственный код, или у вас есть исходный код для библиотеки стороннего разработчика и вы планируете его развернуть в проекте Unity как библиотеку DLL. Данный сценарий не описывает отладку библиотеки DLL, для которой у вас нет исходного кода.
Отладка проекта с управляемой библиотекой DLL, используемой в проекте Unity
Добавьте существующий проект библиотеки DLL в решение Visual Studio, которое создается набором средств Visual Studio для Unity. В ряде случаев вы можете создать новый проект с управляемой библиотекой DLL, который будет содержать компоненты кода проекта Unity. В этом сценарии в решение Visual Studio можно добавить новый проект с управляемой библиотекой DLL.
Existing Item menu.» title=»vstu_debugging_dll_add_existing» data-linktype=»relative-path»/>
В любом случае набор средств Visual Studio для Unity сохраняет ссылку на проект, даже если он должен повторно создать файлы проекта и решения, поэтому эти действия нужно будет выполнить только один раз.
Создайте ссылку на нужный профиль платформы Unity в проекте DLL. В Visual Studio в свойствах проекта DLL для свойства Целевая платформа укажите версию платформы Unity, которую вы используете. Это библиотека базового класса Unity, соответствующая уровню совместимости API, на который ориентирован ваш проект, например библиотека базовых классов Unity full, micro или web. Благодаря этому ваша библиотека DLL не будет вызывать методы платформы, существующие на других платформах или уровнях совместимости, но которые могут отсутствовать в версии платформы Unity, которую вы используете.
Скопируйте библиотеку DLL в папку Asset (ресурсы) своего проекта Unity. В Unity ресурсы представляют собой файлы, которые упаковываются и развертываются вместе с вашим приложением Unity, чтобы их можно было загружать во время выполнения. Так как библиотеки DLL связываются во время выполнения, их необходимо развертывать как ресурсы. Для развертывания в виде ресурса редактору Unity требуется, чтобы библиотеки DLL были помещены в папку Assets вашего проекта Unity. Предусмотрены два способа выполнения этой задачи.
Измените параметры сборки проекта DLL, чтобы добавить выполняемую после сборки задачу, которая скопирует выходные файлы DLL и PDB из выходной папки в папку Активы проекта Unity.
Измените параметры сборки проекта DLL, чтобы сделать выходной папкой папку Assets проекта Unity. Теперь файлы DLL и PDB будут сразу помещаться в папку Assets.
PDB-файлы необходимы для отладки, так как они содержат символы отладки библиотеки DLL и сопоставляют код DLL с формой его исходного кода. Если будет применяться устаревшая среда выполнения, Инструменты Visual Studio для Unity будут использовать сведения из файлов DLL и PDB для создания файла DLL.MDB. Это формат отладочных символов, применяемый устаревшим модулем обработки скрипов Unity. Если будет применяться новая среда выполнения и формат Portable-PDB, Инструменты Visual Studio для Unity не будут пытаться преобразовывать символы, так как новая среда выполнения Unity может самостоятельно обрабатывать файлы Portable-PDB.
См. подробнее сведения о создании PDB-файлов. Если будет применяться новая среда выполнения, убедитесь, что для параметра «Отладочная информация» задано значение «Переносимый» для корректного создания файла Portable PDB. Если будет применяться устаревшая среда выполнения, воспользуйтесь значением «Полный».
Выполните отладку своего кода. Теперь вы можете отлаживать свой исходный код DLL вместе с исходным кодом проекта Unity и использовать все доступные функции, например точки останова и пошаговое выполнение кода.
Сочетания клавиш
Для быстрого доступа средств Unity к функциям Visual Studio можно использовать соответствующие сочетания клавиш. Ниже приведен список таких сочетаний клавиш.
Команда | Сочетание клавиш | Имя контекстной команды |
---|---|---|
Открыть мастер MonoBehavior | CTRL+SHIFT+M | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Открыть обозреватель проектов Unity | ALT+SHIFT+E | View.UnityProjectExplorer |
Доступ к документации по Unity | CTRL+ALT+M, CTRL+H | Help.UnityAPIReference |
Присоединиться к отладчику Unity (проигрыватель или редактор) | значение по умолчанию отсутствует | Debug.AttachUnityDebugger |
Если вас не устраивает сочетание клавиш по умолчанию, его можно изменить. Чтобы узнать, как это сделать, см. статью Определение и настройка сочетаний клавиш в Visual Studio.
Команда | Сочетание клавиш | Имя контекстной команды |
---|---|---|
Открыть мастер MonoBehavior | Cmd+Shift+М | EditorContextMenus.CodeWindow.ImplementMonoBehaviours |
Доступ к документации по Unity | Cmd+’ | Help.UnityAPIReference |
Если вас не устраивает сочетание клавиш по умолчанию, его можно изменить. Сведения о том, как изменить его, см. в разделе «Настройка интегрированной среды разработки».
Visual Studio C# Integration
What does this feature get me?
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
What’s the difference between Express and Pro?
VisualStudio C# 2010 is a product from Microsoft. It comes in an Express and a Profesional edition. The Express edition is free, and you can download it from here.
The Professional edition is not free, you can find out more information about it here.
Unity’s VisualStudio integration allows you to create and maintain VisualStudio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
I’ve got Visual Studio Express, how do I use it?
I’ve got Visual Studio Profesional, how do I use it?
A few things to watch out for:
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently has. This means that some code (especially newer c# features) will not give an error in Visual Studio but will give an error in Unity.
Unity does not regenerate the Visual Studio project files after an AssetServer update, or a SVN update. You can manually ask Unity to regenerate the Visual Studio project files through the menu: Assets->Sync MonoDevelop Project
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Не смотря на то, что Visual Studio поставляется со своим собственным компилятором C#, и вы можете использовать его для проверки ваших скриптов на ошибки, Unity по прежнему использует собственный компилятор C# для компиляции ваших скриптов. Однако использование компилятора Visual Studio все равно очень эффективно, потому что вам не нужно постоянно переключаться в Unity чтобы проверить свои скрипты на наличие ошибок.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Express and Pro
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Did you find this page useful? Please give it a rating:
Visual Studio C# integration
What does this feature get me?
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
What’s the difference between Express and Pro?
VisualStudio C# 2010 is a product from Microsoft. It comes in an Express and a Professional edition. The Express edition is free, and you can download it from here.
The Professional edition is not free, you can find out more information about it here.
Unity’s VisualStudio integration allows you to create and maintain VisualStudio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
I’ve got Visual Studio Express, how do I use it?
I’ve got Visual Studio Professional, how do I use it?
A few things to watch out for:
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently has. This means that some code (especially newer c# features) will not give an error in Visual Studio but will give an error in Unity.
Unity does not regenerate the Visual Studio project files after an AssetServer update, or a SVN update. You can manually ask Unity to regenerate the Visual Studio project files through the menu: Assets->Sync MonoDevelop Project
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright © 2017 Unity Technologies. Publication 5.5-001G 2017-03-29
Unity Code Snippets
Kleber Silva
Unity Code Snippets
Create Unity classes and methods easily.
Features
All Unity code snippets you need. This extension intends to be the complete collection of Unity snippets for Visual Studio Code.
It takes advantage of latest Visual Studio Code snippets features to create the code faster for you.
MonoBehaviour
Editor
ScriptableObject
You never remember the property that goes with the ScriptableObject to create it via Unity create menu? Not a problem.
Instalation
As in any Visual Studio Code Extension you have several options to install:
All the snippets
Start typing the names to create the corresponding snippets.
Some useful code snippets:
If you have any suggestions, open an issue in the Github project page and I’ll add it as soon as I can :).
If you like the color theme of the previews, you can download it here: Base16 Ocean Dark Extended Theme.
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Extensions and Updates menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Specifying the External Script Editor in Unity
Once you’ve installed a code editor, go to Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug C# code that is running 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.
Unity’s Code Optimization setting has two modes.
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. It 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.
To change which mode the Unity Editor starts up in, go to Edit > Preferences > General > Code Optimization On Startup.
In Preferences, you can change the Code Optimization mode that Unity starts in.
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:
Setting breakpoints and attaching to the Editor
In your external code editor, set a breakpoint in the code editor on a line of script code where the debugger should stop. For example, in Visual Studio, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
A breakpoint set in Visual Studio
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
The Attach To Unity button in Visual Studio
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
Visual Studio listing the current instances of Unity available to debug. In this example, there is one instance running in the Editor and one instance running as an Android Plyaer
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
The debugger in Visual Studio when it has stopped at a breakpoint
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
Prevent the device from locking
If the device you are using to debug the application has a screen lock, make sure this is disabled. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. It is best to avoid locking the screen during managed code debugging. If the screen does lock, you should restart the application on the device before the debugger can connect again.
Debugger for Unity
deitry
Unity Debugger Extension for Visual Studio Code
NOTE: This is a fork of an original Unity debugger extension and should be considered as Preview version of Unity debugger extension. See here for the reasons of fork creation. Please refer to this repo for actual source code of extension.
This extension is not officially supported by Unity Technologies.
Use Visual Studio Code to debug your Unity C# projects.
Setup
Open your Unity project folder in the Visual Studio Code.
Select the debug view on the left and click the cogwheel.
Attach to Process Picker
New in version 1.1.0 it is now possible to select which Unity process you want to attach to from a quick pick menu.
In the command palette type «Unity Attach Debugger»
Wait a bit for the Unity processes list to appear at the top of the VS Code window.
Select the Unity process you wish to attach the debugger to.
Usage
Strings in the variable view is truncated to 100 characters, with appended ellipsis. «Example wor. «. To view the entire value of this string add it to the watch fields. In addition, evaluating the variable using the debugger console will reveal the same result.
Building
To build this repository, clone it then get all submodules:
Unity Game Dev Bundle
Jason A. Martin
UNITY GAME DEV BUNDLE
Setting up a great VSC environment to get coding now.
If you’re an Unity game dev who likes Visual Studio Code, this bundle is for you. I’ve bundled up the extensions (with settings) that I use when developing in Unity.
Yes, normal Visual Studio is awesome, but I really love Visual Studio Code and am always telling people about it.
This bundle removes the pain point of getting started. Just click, copy settings and go!
SOME COOL THINGS YOU CAN DO RIGHT AWAY
RECOMMENDED USER SETTINGS
Here’s the user settings I’m currently using. Just open user settings in VSC and paste this JSON into there.
These settings are off a Windows machine, so if you’re on Linux or Windows, change the editor.fontFamily to something appropriate and you can remove the git.path setting.
And dont’ forget to peek at the overall settings because there’s a ton you can tweak.
These settings will get you running right away.
EXTENSIONS BREAKDOWN
Here’s a list of extensions in this pack along with any relevant notes.
GENERAL IMPROVEMENTS
TODO Hightlight :: Adds highlighting when you put a TODO or FIXME in your code. You can add more words and styles too. If you’re using the recommended settings, you already have those plus STUB, REVIEW and DEPRECATED.
TODO Tree :: Nice plugin to see all your TODOs in one place. My settings also grab FIXME, DEPRECATED, STUB and REVIEW. And they have custom icons/colors setup.
Bracket Pair Colorizer :: Colorizes brackets so it’s easier to see what section you’re in.
Indent Rainbow :: Makes it even easier to see what nest you’re in.
Bookmarks :: Creates a way to bookmark a line of code.
Auto Close Tag :: Creates closing tags, which VSC doesn’t do out the box.
Auto Rename Tag :: When you rename a tag, this will rename the closing tag as well.
Prettier :: Adds more code formatting functionality.
Color Highlight :: Shows colors for hex colors it finds in code.
Formatting Toggle :: Quick way to toggle formatting. It puts a one-click toggle in the bottom bar.
Copy Relative Path :: Drop menu off file will now have ‘Copy Path’ that copies over the relative path of the file.
Partial Diff :: Ability to diff text sections in file or in multiple files.
Visual Studio C# integration
What does this feature get me?
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
What’s the difference between Express and Pro?
VisualStudio C# 2010 is a product from Microsoft. It comes in an Express and a Professional edition. The Express edition is free, and you can download it from here.
The Professional edition is not free, you can find out more information about it here.
Unity’s VisualStudio integration allows you to create and maintain VisualStudio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
I’ve got Visual Studio Express, how do I use it?
I’ve got Visual Studio Professional, how do I use it?
A few things to watch out for:
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently has. This means that some code (especially newer c# features) will not give an error in Visual Studio but will give an error in Unity.
Unity does not regenerate the Visual Studio project files after an AssetServer update, or a SVN update. You can manually ask Unity to regenerate the Visual Studio project files through the menu: Assets->Sync MonoDevelop Project
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright © 2017 Unity Technologies. Publication: 5.6-001N. Built: 2017-07-12.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Integrated development environment (IDE) support
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 (default IDE on Windows and macOS)
Visual Studio is installed by default when you install Unity on Windows and macOS. On Windows, you can choose to exclude it when you select which components to download and install. Visual Studio is set as the External Script Editor in Preferences (menu: Edit > Preferences > External Tools > External Script Editor). With this option enabled, Unity launches Visual Studio and uses it as the default editor for all script files.
On macOS, Unity includes 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:
On Windows, Unity also includes Visual Studio 2017 Community.
Visual Studio Code (Windows, macOS, Linux)
Unity supports opening scripts in Visual Studio Code (VS Code). To open scripts in VS Code, select it as the External Script Editor in the Editor Preferences (menu: Edit > Preferences > External Tools > External Script Editor). 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:
JetBrains Rider (Windows, macOS, Linux)
Unity supports opening scripts in JetBrains Rider. To open scripts in Rider, select it as the External Script Editor in the Editor Preferences (menu: Edit > Preferences > External Tools > External Script Editor).
Visual Studio C# integration
Unity integrates with Microsoft Visual Studio through the Code Editor Package for Visual Studio. This package is pre-installed when you install Unity. If Visual Studio is installed at the time you install Unity, then Unity uses Visual Studio to open and edit scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary by default.
The Visual Studio Editor in the Package Manager Window
Set Visual Studio as your default script editor
Unity automatically uses Visual Studio as its default script editor if Visual Studio is installed when you install Unity, or if you install Visual Studio as part of the Unity installation process. You can install Visual Studio as a module into an existing Unity installation. For more information, see Downloading and installing Editors and modules with the Unity Hub.
To set your default script editor manually:
A: The External Script Editor dropdown menu, which displays the name and version of the selected script editor.
B: The name and version of the Unity package that integrates with the selected script editor.
Unity uses Visual Studio’s C# compiler to compile scripts. When you use the Visual Studio Editor package with Visual Studio, both Unity and Visual Studio display details of any errors in your scripts.
Visual Studio C# Integration
What does this feature get me?
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
What’s the difference between Express and Pro?
VisualStudio C# 2010 is a product from Microsoft. It comes in an Express and a Profesional edition. The Express edition is free, and you can download it from here.
The Professional edition is not free, you can find out more information about it here.
Unity’s VisualStudio integration allows you to create and maintain VisualStudio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
I’ve got Visual Studio Express, how do I use it?
I’ve got Visual Studio Profesional, how do I use it?
A few things to watch out for:
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently has. This means that some code (especially newer c# features) will not give an error in Visual Studio but will give an error in Unity.
Unity does not regenerate the Visual Studio project files after an AssetServer update, or a SVN update. You can manually ask Unity to regenerate the Visual Studio project files through the menu: Assets->Sync MonoDevelop Project
Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.
Copyright © 2016 Unity Technologies. Publication 5.4-X
Visual Studio Tools for Unity
Overview
Visual Studio Tools for Unity includes a rich set of features that enhances writing and debugging Unity C# scripts and working with Unity projects.
Available for Windows and macOS
Visual Studio Tools for Unity is available for free and supports Visual Studio 2017 Community, Professional, and Enterprise and newer. We recommend downloading and using the latest version of Visual Studio..
Visual Studio Tools for Unity is available for free and included in every installation of Visual Studio for Mac 2017 and newer. We recommend downloading and using the latest version of Visual Studio for Mac..
Visit the Visual Studio Tools for Unity getting started with Tools For Unity. for more information about installation and setup.
Supported Unity versions
Visual Studio Editor Unity package
Unity 2020.1 and newer require a Unity Package for external editor tools like Visual Studio and Visual Studio for Mac. Documentation to Learn more about these changes in the Unity blog post..
The getting started section includes more information on the configuration of the Visual Studio Editor package.
The latest version of the Visual Studio Editor package is recommended.
Visual Studio | Minimum Unity version | Minimum package version |
---|---|---|
2022 | Unity 2019.4 | Visual Studio Editor 2.0.11 |
2019 | Unity 2017.4 | Visual Studio Editor 2.0.0 |
2017 | Not recommended | N/A |
Visual Studio for Mac | Minimum Unity version | Minimum package version |
---|---|---|
2022 | Unity 2019.4 | Visual Studio Editor 2.0.11 |
2019 | Unity 2017.4 | Visual Studio Editor 2.0.0 |
2017 | Not recommended | N/A |
Features
Unity Event Functions
Generate code for multiple Unity Event Functions and their comments using вЊ+Shift+M.
Quickly fix any parameter mistakes in Event Functions that were added manually with quick-fix suggestions.
High-performance debugger
Visual Studio Tools for Unity supports the robust debugging features that you expect from Visual Studio:
Quick fixes and refactoring suggestions
Write better code that captures the best practices with Visual Studio’s deep understanding of Unity projects.
CodeLens hints
Identify where code is called from using CodeLens hints that show implicit calls from Unity assets. Select the hint to see a list of implicit calls. Selecting a specific call will navigate directly to the object in the Unity Editor.
Quickly distinguish your code from Unity methods with hints for every Unity Event Function.
Unity Project Explorer
Display project files in a way that matches the Hierarchy Window in the Unity Editor.
Unity project view
Visual Studio for Mac automatically displays project files in a way that match the Hierarchy Window in the Unity Editor.
Unity documentation
View Unity documentation directly in tooltips when inspecting code.
Quickly search Unity documentation by highlighting a class or method name, then selecting the Help > Unity API Reference menu item.
Support for shaders
Syntax highlighting and auto-complete for shader files.
Support for assembly definition files
Edit Unity Assembley Definition (.asmdef) files directly in Visual Studio with keyword coloring and completions.
Run and debug unit tests
Write, run, and debug unit tests directly in Visual Studio for Mac.
Automatically refresh Unity assets
Spend less time switching back and forth between Unity and Visual Studio. Changes to code are automatically updated in Unity when files are saved.
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Extensions and Updates menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Unity Preferences
When the code editor is installed, go to Unity > Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug script code running in the Unity Editor when the Unity Editor is in Play Mode. Before attempting to debug, ensure the Editor Attaching option is enabled in the Unity Preferences. This option causes the Editor to use Just In Time (JIT) compilation to execute managed code with debugging information.
First, set a breakpoint in the code editor on a line of script code where the debugger should stop. In Visual Studio for example, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
Prevent the device from locking
If the device you are using to debug the application has a screen lock, make sure this is disabled. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. It is best to avoid locking the screen during managed code debugging. If the screen does lock, you should restart the application on the device before the debugger can connect again.
2018–09–06 Page published with editorial review
Managed Code Debugging added in 2018.2
Did you find this page useful? Please give it a rating:
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Extensions and Updates menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Unity Preferences
When the code editor is installed, go to Unity > Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug script code running in the Unity Editor when the Unity Editor is in Play Mode. Before attempting to debug, ensure the Editor Attaching option is enabled in the Unity Preferences. This option causes the Editor to use Just In Time (JIT) compilation to execute managed code with debugging information.
First, set a breakpoint in the code editor on a line of script code where the debugger should stop. In Visual Studio for example, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
Prevent the device from locking
If the device you are using to debug the application has a screen lock, make sure this is disabled. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. It is best to avoid locking the screen during managed code debugging. If the screen does lock, you should restart the application on the device before the debugger can connect again.
2018–09–06 Page published with editorial review
Managed Code Debugging added in 2018.2
Did you find this page useful? Please give it a rating:
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Get Tools and Features… menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Specifying the External Script Editor in Unity
Once you’ve installed a code editor, go to Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug C# code that is running 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.
Unity’s Code Optimization setting has two modes.
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. It 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.
To change which mode the Unity Editor starts up in, go to Edit > Preferences > General > Code Optimization On Startup.
In Preferences, you can change the Code Optimization mode that Unity starts in.
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:
Setting breakpoints and attaching to the Editor
In your external code editor, set a breakpoint in the code editor on a line of script code where the debugger should stop. For example, in Visual Studio, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
A breakpoint set in Visual Studio
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
The Attach To Unity button in Visual Studio
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
Visual Studio listing the current instances of Unity available to debug. In this example, there is one instance running in the Editor and one instance running as an Android Plyaer
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
The debugger in Visual Studio when it has stopped at a breakpoint
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
Android on Chrome OS
Unity cannot automatically discover Chrome OS devices. To initiate a connection, connect to the device through Android Debug Bridge (adb) by its IP address and then enter the IP address manually in the debugger dialog.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
Prevent the device from locking
If the device you are using to debug the application has a screen lock, make sure this is disabled. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. It is best to avoid locking the screen during managed code debugging. If the screen does lock, you should restart the application on the device before the debugger can connect again.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Visual Studio C# integration
What does this feature get me?
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
What’s the difference between Express and Pro?
VisualStudio C# 2010 is a product from Microsoft. It comes in an Express and a Professional edition. The Express edition is free, and you can download it from here.
The Professional edition is not free, you can find out more information about it here.
Unity’s VisualStudio integration allows you to create and maintain VisualStudio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
I’ve got Visual Studio Express, how do I use it?
I’ve got Visual Studio Professional, how do I use it?
A few things to watch out for:
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently has. This means that some code (especially newer c# features) will not give an error in Visual Studio but will give an error in Unity.
Unity does not regenerate the Visual Studio project files after an AssetServer update, or a SVN update. You can manually ask Unity to regenerate the Visual Studio project files through the menu: Assets->Sync MonoDevelop Project
Did you find this page useful? Please give it a rating:
Integrated development environment (IDE) support
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 (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:
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:
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.
Набор средств Visual Studio для Unity
Обзор
Инструменты Visual Studio для Unity содержат обширный набор функций, повышающих эффективность написания и отладки скриптов C# для Unity и работы с проектами Unity.
Доступно для Windows и macOS
Инструменты Visual Studio для Unity являются бесплатными и поддерживают Visual Studio 2017 Community, Professional, Enterprise и более поздние версии. Рекомендуется скачать и использовать последнюю версию Visual Studio.
Инструменты Visual Studio для Unity являются бесплатными и включены в каждую установку Visual Studio для Mac 2017 и более поздних версий. Рекомендуется скачать и использовать последнюю версию Visual Studio для Mac.
Дополнительные сведения об установке и настройке см. в средствах Visual Studio для Unity для Unity.
Поддерживаемые версии Unity
Пакет Unity редактора Visual Studio
Для Unity 2020.1 и более поздних версий требуется пакет Unity для внешних инструментов редактора, таких как Visual Studio и Visual Studio для Mac. Документация для получения дополнительных сведений об этих изменениях в записи блога по Unity.
В разделе о начале работы содержатся дополнительные сведения о конфигурации пакета редактора Visual Studio.
Рекомендуется использовать последнюю версию пакета редактора Visual Studio.
Visual Studio | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Недоступно |
Visual Studio для Mac | Минимальная версия Unity | Минимальная версия пакета |
---|---|---|
2022 | Unity 2019.4 | Редактор Visual Studio 2.0.11 |
2019 | Unity 2017.4 | Редактор Visual Studio 2.0.0 |
2017 | Не рекомендуется | Н/Д |
Компоненты
Функции событий Unity
Создавайте код для нескольких функций событий Unity и их комментариев с помощью ⌘+Shift+M.
Быстро исправьте ошибки параметров в функциях событий, которые были добавлены вручную, с помощью предложений по быстрому исправлению.
Высокопроизводительный отладчик
Инструменты Visual Studio для Unity поддерживают надежные функции отладки, характерные для Visual Studio:
Быстрые исправления и предложения по рефакторингу
Напишите эффективный код, сочетающий в себе лучшие методики и глубокое понимание проектов Unity Visual Studio.
Указания CodeLens
Определяйте места, откуда вызывается код, используя указания CodeLens, которые показывают неявные вызовы из ресурсов Unity. Выберите указание, чтобы просмотреть список неявных вызовов. При выборе конкретного вызова выполняется переход непосредственно к объекту в редакторе Unity.
Быстро отличайте код от методов Unity с помощью указаний для каждой функции события Unity.
Обозреватель проектов Unity
Отображайте файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Представление проекта Unity
Visual Studio для Mac автоматически отображает файлы проекта в соответствии с представлением в окне иерархии в редакторе Unity.
Документация по Unity
Просматривайте документацию по Unity непосредственно во всплывающих подсказках при проверке кода.
Чтобы быстро найти документацию по Unity, выделите имя класса или метода, а затем выберите пункт меню » > Справка по API Unity».
Поддержка шейдеров
Выделение синтаксиса и автоматическое завершение для файлов шейдера.
Поддержка файлов определения сборки
Редактируйте файлы определения сборки Unity (.asmdef) непосредственно в Visual Studio с помощью раскраски и завершения ключевых слов.
Выполнение и отладка модульных тестов
Создавайте, выполняйте и отлаживайте модульные тесты непосредственно в Visual Studio для Mac.
Автоматическое обновление ресурсов Unity
Тратить меньше времени на переключение между Unity и Visual Studio. Изменения кода автоматически обновляются в Unity при сохранении файлов.
Unity-Technologies/vscode-unity-debug
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Unity Debugger Extension for Visual Studio Code
This extension is not officially supported by Unity Technologies.
Use Visual Studio Code to debug your Unity C# projects.
Open your Unity project folder in the Visual Studio Code.
Select the debug view on the left and click the cogwheel.
Attach to Process Picker
New in version 1.1.0 it is now possible to select which Unity process you want to attach to from a quick pick menu.
In the command palette type «Unity Attach Debugger»
Wait a bit for the Unity processes list to appear at the top of the VS Code window.
Select the Unity process you wish to attach the debugger to.
Strings in the variable view is truncated to 100 characters, with appended ellipsis. «Example wor. «. To view the entire value of this string add it to the watch fields. In addition, evaluating the variable using the debugger console will reveal the same result.
To build this repository, clone it then get all submodules:
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Extensions and Updates menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Unity Preferences
When the code editor is installed, go to Unity > Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug script code running in the Unity Editor when the Unity Editor is in Play Mode. Before attempting to debug, ensure the Editor Attaching option is enabled in the Unity Preferences. This option causes the Editor to use Just In Time (JIT) compilation to execute managed code with debugging information.
First, set a breakpoint in the code editor on a line of script code where the debugger should stop. In Visual Studio for example, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
2018–09–06 Page published with editorial review
Managed Code Debugging added in 2018.2
Did you find this page useful? Please give it a rating:
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
[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.
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 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:
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.
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:
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.
Your omnisharp.json file should end up looking like this:
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:
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:
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.
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 |
---|---|
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.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Express and Pro
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Even though Visual Studio comes with its own C# compiler, and you can use it to check if you have errors in your c# scripts, Unity still uses its own C# compiler to compile your scripts. Using the Visual Studio compiler is still quite useful, because it means you don’t have to switch to Unity all the time to check if you have any errors or not.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Did you find this page useful? Please give it a rating:
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Professional and Enterprise
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Did you find this page useful? Please give it a rating:
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Express and Pro
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Не смотря на то, что Visual Studio поставляется со своим собственным компилятором C#, и вы можете использовать его для проверки ваших скриптов на ошибки, Unity по прежнему использует собственный компилятор C# для компиляции ваших скриптов. Однако использование компилятора Visual Studio все равно очень эффективно, потому что вам не нужно постоянно переключаться в Unity чтобы проверить свои скрипты на наличие ошибок.
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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 Bar
Unity’s Code Optimization setting has two modes:
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.
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.
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:
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:
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.
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.
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
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
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.
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
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.
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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 Bar
Unity’s Code Optimization setting has two modes:
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.
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.
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:
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:
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.
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.
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
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
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.
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
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.
Integrated development environment (IDE) support
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 (default IDE on Windows and macOS)
Visual Studio is installed by default when you install Unity on Windows and macOS. On Windows, you can choose to exclude it when you select which components to download and install. Visual Studio is set as the External Script Editor in Preferences (menu: Unity > Preferences > External Tools > External Script Editor). With this option enabled, Unity launches Visual Studio and uses it as the default editor for all script files.
On macOS, Unity includes 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:
On Windows, Unity also includes Visual Studio 2017 Community.
Visual Studio Code (Windows, macOS, Linux)
Unity supports opening scripts in Visual Studio Code (VS Code). To open scripts in VS Code, select it as the External Script Editor in the Editor Preferences (menu: Unity > Preferences > External Tools > External Script Editor). 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:
JetBrains Rider (Windows, macOS, Linux)
Unity supports opening scripts in JetBrains Rider. To open scripts in Rider, select it as the External Script Editor in the Editor Preferences (menu: Unity > Preferences > External Tools > External Script Editor).
Debugging C# code in Unity
Using a debugger allows you to inspect your source code while your application or game is running. Unity supports debugging of C# code using the following code editors:
Visual Studio (with the Visual Studio Tools for Unity plug-in)
Visual Studio for Mac
Visual Studio Code
Although these code editors vary slightly in the debugger features they support, all provide basic functionality like break points, single stepping, and variable inspection.
Configuring the code editor
Visual Studio (Windows)
If Visual Studio is already installed on your computer, use its Tools > Extensions and Updates menu 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, use its Extension Manager to locate and install the Visual Studio Tools for Unity plug-in.
JetBrains Rider
The default installation of JetBrains Rider can debug code in Unity on Windows or Mac. Please visit the JetBrains website to install it.
VS Code
VS Code requires you to install an extension to debug code in Unity. Please follow the instructions specific to this extension to install it.
Unity Preferences
When the code editor is installed, go to Unity > Preferences > External Tools and set the External Script Editor to your chosen code editor.
Debugging in the Editor
You can debug script code running in the Unity Editor when the Unity Editor is in Play Mode. Before attempting to debug, ensure the Editor Attaching option is enabled in the Unity Preferences. This option causes the Editor to use Just In Time (JIT) compilation to execute managed code with debugging information.
First, set a breakpoint in the code editor on a line of script code where the debugger should stop. In Visual Studio for example, click on the column to the left of your code, on the line you want to stop the debugger (as shown below). A red circle appears next to the line number and the line is highlighted.
Next, attach the code editor to the Unity Editor. This option varies depending on the code editor, and is often a different option from the code editor’s normal debugging process. In Visual Studio, the option looks like this:
Some code editors may allow you to select an instance of Unity to debug. For example, in Visual Studio, the Debug > Attach Unity Debugger option exposes this capability.
When you have attached the code editor to the Unity Editor, return to the Unity Editor and enter Play Mode. When the code at the breakpoint is executed, the debugger will stop, for example:
While the code editor is at a breakpoint, you can view the contents of variables step by step. The Unity Editor will be unresponsive until you choose the continue option in the debugger, or stop debugging mode.
Debugging in the Player
To debug script code running in a Unity Player, ensure that you enable the “Development Build” and ”Script Debugging” options before you build the Player (these options are located in File > Build Settings). Enable the “Wait For Managed Debugger” option to make the Player wait for a debugger to be attached before it executes any script code.
To attach the code editor to the Unity Player, select the IP address (or machine name) and port of your Player. In Visual Studio, the drop-down menu on the “Attach To Unity” option looks like this:
The Debug > Attach Unity Debugger option looks like this:
Make sure you attach the debugger to the Player, and not to the Unity Editor (if both are running). When you have attached the debugger, you can proceed with debugging normally.
Debugging on Android and iOS devices
Android
When debugging a Player running on an Android device, connect to the device via USB or TCP. For example, to connect to an Android device in Visual Studio (Windows), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
In this case, the phone is connected via USB and Wi-Fi on the same network as the workstation running the Unity Editor and Visual Studio.
When debugging a Player running on an iOS device, connect to the device via TCP. For example, to connect to an iOS device in Visual Studio (Mac), select Debug > Attach Unity Debugger option. A list of devices running a Player instance will appear:
Troubleshooting the debugger
Most problems with the debugger occur because the code editor is unable to locate the Unity Editor or the Player. This means that it 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. Here 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 code editor to any Unity Editor or Unity Player on the local network that has debugging enabled. When attaching the debugger to ensure that you are attaching to the correct 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 uses. If the code editor cannot find the Unity instance you expect it to find, try to attach the Unity Profiler to that instance. If the Unity Profiler cannot find it either, a firewall might exist on the machine which you are running the code editor on or the machine which you are running the Unity instance on (or possibly both). If a firewall is in place, see the information about firewall settings below.
Ensure the device has only one active network interface
Many devices have multiple network interfaces. For example, a mobile phone may have both an active cellular connection and an active Wi-Fi connection. To properly connect the debugger for TCP, the IDE needs to make a network connection to the correct interface on the device. If you plan to debug via Wi-Fi, for example, make sure you put the device in airplane mode to disable all other interfaces, then enable Wi-Fi.
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 via a TCP connection. On most Unity platforms, this TCP connection occurs on an arbitrarily chosen port. Normally, you should not need to know this port, as the code editor should detect it automatically. If that does not work, try to 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 both the port on the machine running the code editor, and the machine running the Unity instance.
Verify the managed debugging information is available
Prevent the device from locking
If the device you are using to debug the application has a screen lock, make sure this is disabled. Screen locks cause the debugger to disconnect, and prevent it from re-connecting. It is best to avoid locking the screen during managed code debugging. If the screen does lock, you should restart the application on the device before the debugger can connect again.
Visual Studio C# integration
Benefits of using Visual Studio
A more sophisticated C# development environment. Think smart autocompletion, computer-assisted changes to source files, smart syntax highlighting and more.
The difference between Community, Express and Pro
VisualStudio C# is an Integrated Development Environment (IDE) tool from Microsoft. Visual Studio now comes in three editions, Community (free to use) Professional (paid) and Enterprise (paid). A comparison of feature differences between versions is available on the Visual Studio website.
Unity’s Visual Studio integration allows you to create and maintain Visual Studio project files automatically. Also, VisualStudio will open when you double click on a script or on an error message in the Unity console.
Using Visual Studio with Unity
Follow these steps to configure the Unity Editor to use Visual Studio as its default IDE:
In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.
External Tool Settings
Next, doubleclick a C# file in your project. Visual Studio should automatically open that file for you.
You can edit the file, save, and switch back to Unity to test your changes.
A few things to watch out for
Visual Studio’s C# compiler has some more features than Unity’s C# compiler currently supports. This means that some code (especially newer c# features) will not throw an error in Visual Studio but will in Unity.
Did you find this page useful? Please give it a rating:
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:
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.
Configure the code editor
Visual Studio (Windows)
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 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 Bar
Unity’s Code Optimization setting has two modes:
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.
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.
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:
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:
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.
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.
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
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 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
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.
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
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.
Источники:
- http://code.visualstudio.com/docs/other/unity
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity
- http://marketplace.visualstudio.com/items?itemName=PradeepPuriGoswami.unity-code
- http://github.com/microsoft/vscode-docs/blob/main/docs/other/unity.md
- http://vscode-docs.readthedocs.io/en/stable/runtimes/unity/
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/using-visual-studio-tools-for-unity
- http://docs.unity3d.com/2021.1/Documentation/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/2019.4/Documentation/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/ru/2020.2/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/2021.2/Documentation/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2022.1/Documentation/Manual/VisualStudioIntegration.html
- http://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity
- http://marketplace.visualstudio.com/items?itemName=Unity.unity-debug
- http://docs.unity3d.com/2022.1/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2019.4/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/using-visual-studio-tools-for-unity
- http://docs.unity3d.com/ru/2021.1/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/ru/2020.2/Manual/VisualStudioIntegration.html
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?view=vs-2017
- http://marketplace.visualstudio.com/items?itemName=Tobiah.unity-tools
- http://github.com/dotBunny/VSCode
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/visual-studio-tools-for-unity?view=vsmac-2022
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/visual-studio-tools-for-unity
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/using-visual-studio-tools-for-unity?view=vs-2022
- http://docs.unity3d.com/530/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/ru/2019.4/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2018.4/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2018.3/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/550/Documentation/Manual/VisualStudioIntegration.html
- http://marketplace.visualstudio.com/items?itemName=kleber-swf.unity-code-snippets
- http://docs.unity3d.com/2020.1/Documentation/Manual/ManagedCodeDebugging.html
- http://marketplace.visualstudio.com/items?itemName=deitry.unity-debug
- http://marketplace.visualstudio.com/items?itemName=JasonAMartin.unity-game-dev-bundle
- http://docs.unity3d.com/560/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2020.2/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/ru/2021.1/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/2021.2/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/540/Documentation/Manual/VisualStudioIntegration.html
- http://docs.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/visual-studio-tools-for-unity
- http://docs.unity3d.com/2019.1/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2018.3/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2019.3/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2017.1/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2022.1/Documentation/Manual/ScriptingToolsIDEs.html
- http://docs.microsoft.com/ru-ru/visualstudio/gamedev/unity/get-started/visual-studio-tools-for-unity?view=vs-2017
- http://github.com/Unity-Technologies/vscode-unity-debug
- http://docs.unity3d.com/2018.2/Documentation/Manual/ManagedCodeDebugging.html
- http://vscode-eastus.azurewebsites.net/docs/other/unity
- http://docs.unity3d.com/2017.3/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2019.1/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/ru/2018.4/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2020.3/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2021.2/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/ru/2018.4/Manual/ScriptingToolsIDEs.html
- http://docs.unity3d.com/2018.4/Documentation/Manual/ManagedCodeDebugging.html
- http://docs.unity3d.com/2018.2/Documentation/Manual/VisualStudioIntegration.html
- http://docs.unity3d.com/2022.2/Documentation/Manual/ManagedCodeDebugging.html