Интеграция Visual Studio C#
Более сложная среда разработки C#. Подумайте об интеллектуальном автодополнении, компьютерных изменениях исходных файлов, умной подсветке синтаксиса и многом другом.
Разница между Community, Professional и Enterprise
VisualStudio C# — это инструмент интегрированной среды разработки (IDE) от Microsoft. Теперь Visual Studio поставляется в трех версиях: Community (бесплатно) Профессиональный (платный) и Корпоративный (платный). Сравнение различий между версиями доступно на веб-сайте Visual Studio.
Интеграция Unity с Visual Studio позволяет автоматически создавать и поддерживать файлы проекта Visual Studio. Кроме того, VisualStudio открывается при двойном щелчке скрипта или сообщения об ошибке в консоли Unity.
Использование Visual Studio с Unity
Выполните следующие действия, чтобы настроить редактор Unity для использования Visual Studio в качестве интегрированной среды разработки по умолчанию:
В Unity перейдите в раздел Edit > Preferences и убедитесь, что Visual Studio выбран в качестве предпочитаемого внешнего редактора.
Настройки внешнего инструмента
Затем дважды щелкните файл C# в своем проекте. Visual Studio должна автоматически открыть этот файл для вас.
Вы можете отредактировать файл, сохранить его и вернуться в Unity, чтобы проверить свои изменения.
На что следует обратить внимание
Несмотря на то, что Visual Studio поставляется с собственным компилятором C#, его можно использовать для проверки наличия ошибок в скриптах c# Кусок кода, позволяющий создавать собственные Компоненты, запускать игровые события, изменять свойства Компонентов с течением времени и реагировать на действия пользователя любым удобным для вас способом. Подробнее
См. Словарь , Unity по-прежнему использует собственный компилятор C# для компиляции ваших скриптов. Использование компилятора Visual Studio по-прежнему весьма полезно, поскольку это означает, что вам не нужно постоянно переключаться на Unity, чтобы проверить, есть ли у вас какие-либо ошибки или нет.
Компилятор Visual Studio C# имеет несколько больше функций, чем в настоящее время поддерживает компилятор Unity C#. Это означает, что некоторый код (особенно новые функции C#) не будет вызывать ошибку в Visual Studio, но будет вызывать ее в Unity.
Unity автоматически создает и поддерживает файлы Visual Studio .sln и .csproj. Всякий раз, когда кто-то добавляет/переименовывает/перемещает/удаляет файл из Unity, Unity повторно создает файлы .sln и .csproj. Вы также можете добавлять файлы в свое решение из Visual Studio. Затем Unity импортирует эти новые файлы, и в следующий раз, когда 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:
- Go to Edit > Preferences.
- Open the External Tools menu.
- Click on the External Script Editor dropdown and select Microsoft Visual Studio. The appearance of this option changes depending on the version of Microsoft Visual Studio you have installed.
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 automatically creates and maintains a Visual Studio .sln and .csproj file. You can control whether Unity generates .csproj files for certain elements of your project in the External Tools menu in the Preferences window, as in the above screenshot. Enable or disable the checkboxes to toggle whether Unity generates .csproj files for a given option.
Unity regenerates the .sln and .csproj files in your project whenever a contributor makes changes to the state of a file, for example, editing an existing file or creating a new one. You can also add files to your solution from Visual Studio. Unity imports any new files, and the next time Unity creates the project files again, it creates them with the new files included.
Name already in use
visualstudio-docs / gamedev / unity / get-started / getting-started-with-visual-studio-tools-for-unity.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
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.
. image type=»content» source=»../media/vs/unity-workload.png» alt-text=»Screenshot of the game development with Unity workload checkbox in the installer.».
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.
[!NOTE] 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.
[!TIP] Projects are created using the Unity Editor and not Visual Studio.
[!NOTE] 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.
. image type=»content» source=»../media/vsm/unity-workload.png» alt-text=»Screenshot of the Extension Manager view showing Visual Studio for Mac Tools for Unity 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.
. image type=»content» source=»../media/vs/preferences-external-tools.png» alt-text=»Screenshot of the External Tools preference menu in the Unity Editor on Windows.».
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.
- Select Browse. from the dropdown list.
- Navigate to the Common7/IDE directory inside your Visual Studio installation directory and select devenv.exe. Then select Open.
- For Unity 2019 and older only, confirm that Editor Attaching is selected.
- Close the Preferences dialog to complete the configuration process.
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.
. image type=»content» source=»../media/vsm/preferences-external-tools.png» alt-text=»Screenshot of the External Tools preference menu in the Unity Editor on macOS.».
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.
In the Unity Editor, select the Windows > Package Manager menu.
Select the Visual Studio Editor package.
If a new version is available, select Update.
. image type=»content» source=»../media/vs/unity-package-manager.png» alt-text=»Screenshot of the Package Manager window in the Unity Editor on Windows.».
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.
In the Unity Editor, select the Windows > Package Manager menu.
Select the Visual Studio Editor package.
If a new version is available, select Update.
. image type=»content» source=»../media/vsm/unity-package-manager.png» alt-text=»Screenshot of the Package Manager window in the Unity Editor on Mac.».
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.
. image type=»content» source=»../media/vs/check-for-updates.png» alt-text=»Screenshot of the Check for Updates menu in Visual Studio Help menu.».
If an update is available, the Visual Studio Installer shows a new version. Select Update.
. image type=»content» source=»../media/vs/click-to-update.png» alt-text=»Screenshot of Visual Studio Installer with the Updates.».
Select the Visual Studio for Mac > Check for Updates. menu to open the Visual Studio Update dialog.
. image type=»content» source=»../media/vsm/check-for-updates.png» alt-text=»Screenshot of the Check for Updates menu in Visual Studio Help menu.».
If an update is available, Visual Studio Update shows a new version, select Restart and Install Updates.
Integrating Visual Studio with Unity for Game development.
You just started learning game development with Unity and now you need to write a script (let’s say you want to provide basic movement capabilities to your character). So, you figured out that you need to install Visual Studio, so you downloaded and installed it in your system.
Now, that you have both Unity and Visual Studio installed, you decide to proceed forward, so you click on the C# script that you have created and Snap! You realise you are not getting any recommendations or code completions from the IDE for the Unity components.
But isn’t that what an IDE is supposed to do? Make your life a little easier by completing the code for you and making all the methods in a class readily available to you? So what went wrong?
Well, do not worry! You have missed a very simple step due to which it’s not working as expected and this is what this article intends to help you fix.
In this post, I will guide you through the following:
- Downloading the correct Visual studio.
- Creating a new C# script in Unity.
- Integrating Visual Studio with Unity.
Downloading the correct Visual studio.
Here, you can find the link to download the Community edition of Visual Studio .
NOTE: The Professional and Enterprise editions are paid.
Depending on your platform, download the correct Visual Studio. Also, I wouldn’t recommend downloading ‘Visual Studio Code’ as it is just a code editor, not a fully integrated IDE unlike the Visual Studio. I’ll be demonstrating the MacOS version here.
Let the downloading and installation happen in the background. Meanwhile, we will see how to create a C# script in Unity.
Creating a new C# script with Unity.
Open Unity and look for the ‘Project Hierarchy’ panel. You will be able to see the ‘Assets’ folder here. (In my case, I have ‘Assets’ and ‘Packages’)
Step-1: Select the Root ‘Assets’ directory
Step-2: Create a new Scripts Directory
Right click on the Assets folder shown in the previous image and create a new ‘Folder’ as shown in the image below and name it as ‘Scripts’
Once you’re done, you will have something like this:
Step-3: Create a New C# Script
Right click on the Scripts directory and create a new C# Script as shown in the image below and provide it a proper name. Since we were trying to bring the protagonist to life, we will name it as ‘player’ without specifying any format.
You will now have a C# script generated with the basic code which can be seen in the ‘Inspector’ panel.
DO NOT click on the C# script yet. Now, we will go back and check if the Visual studio installation has finished. If it hasn’t, wait for it to finish since you don’t have any application capable of running a C# script yet.
Once installed successfully, we are ready to proceed further!
Integrating Visual Studio with Unity.
This is the most important part so make sure that you follow all the steps in this section.
Step-1: Open Preferences
Click on the Unity tab and select ‘Preferences’ as shown in the image below.
Step-2: Select External Tools
Step-3: Select Visual Studio from the Dropdown
Click on the dropdown in the external tools section and select ‘Visual Studio’.
NOTE: It will not be reflected if the Visual Studio installation has not finished yet.
In case Visual Studio has finished installing and you are still not able to see it in the dropdown, click on Browse…, navigate to Applications on your Mac, click on Visual Studio and select ‘Open’ as shown in the image below.
Now that Visual Studio is integrated with Unity, select the ‘player’ C# script which we had created in the previous section and wait for it to launch.
Let’s try the same thing which we had tried before, we will see if we can utilise the full potential of the IDE:
And that's it! We have now successfully integrated Visual studio with Unity and now are one step closer to bring our character to life.