rider редактор кода unity
Integrating Rider 2018.2 and the Unity Editor
Rider 2018.1 introduced deep integration with the Unity Editor, allowing you to run unit tests, view Unity console log entries and control play mode, all without leaving Rider. In our third post looking at Rider 2018.2 and Unity, we’ll look at what’s new in Editor integration.
Installation and first use
The easiest way to get started with Rider and Unity is to load an existing solution, at which point we’ll automatically install a plugin into your Unity project. When you switch back to Unity, the plugin initialises, sets Rider as the default external editor and you’re all set. The plugin makes sure the generated C# projects are compatible with Rider, and will set up the inter-process communication that lets Rider run tests, view logs and so on.
But there’s a little bit of a chicken and egg scenario here. What happens when there aren’t any solution files? Unity generates these files, and makes sure they’re up to date when you double click a C# file. But they’re not usually checked into source control. So how do you open a project without solution files?
Of course, once Rider is set as the default external editor in Unity, you can double click a C# file and Unity will open Rider for you. But we also received feedback that users were trying to open a Unity project using Rider’s Open Folder feature. This is mostly intended for working with web files, and not C# projects, which require MSBuild files. Without important context from project files (e.g. target framework version, references, etc.) Rider can’t show the C# features we all know and love, such as code completion or inspections, and this was understandably leaving users frustrated.
The good news is that we’ve addressed this in Rider 2018.2! If you try and open a fresh Unity project as a folder, Rider will now notify you that Unity and C# functionality is unavailable until the project is reopened correctly. It will also prompt you to install the plugin. Once you’ve clicked the action link, Rider will install the plugin and then prompt you to switch back to Unity, at which point Unity will load the plugin, set the default external editor and generate the project files. You can now reload the solution correctly.
(Of course, you can also set Rider as the default external editor in Unity’s preferences – recent versions of Unity will recognise when Rider is installed and automatically add it to the list of available editors. Once selected, double clicking a C# file will generate the solution, open it in Rider, and then the plugin is automatically installed.)
Log viewer
One of the cool features of Rider’s deep Unity integration is the ability to capture Unity’s Console log messages and bring them into Rider’s UI, with parsed, clickable stack traces. We’ve made a couple of nice updates in this release.
Firstly, we’ve added a text filter. Just start typing in the search field at the bottom of the window, and we’ll narrow down the list by only show matching items. Hit enter to change focus to the list and navigate with the cursor keys.
And if there are too many log entries? Well, you can now collapse similar items, using the toggle button in the toolbar. Once selected, Rider will only show a single item, with the number of merged items shown in brackets at the end of the message.
And finally, we can now open editor and player log files in Rider’s editor. Simply open the options menu in the Unity log viewer tool window (the cog in the top right of the tool window) and select Open Unity Editor Log or Open Unity Editor Player Log. Note that these log files are the Unity editor’s own logs, or logs from a standalone player, rather than the messages logged to Unity’s Console.
Working with class libraries
With the advent of Assembly Definition Files, Unity now has a story for splitting a solution up into separate assemblies, with the architectural and build time advantages this gives. But we know that there are still a lot of Unity developers who create a separate solution for class libraries that are then added as binary references to a Unity project. Wouldn’t it be nice if all those lovely Unity project integration features were available to these class library projects? Well, now they are!
If you have a class library project, with solution files living in the root of the Unity project (in the same location as the generated solution file), Rider will now enable the same rich integration features for class library projects.
This means you’ll get the log viewer, the play/pause/step buttons to control Unity’s play mode, and also automatic Attach to Unity Editor and Attach to Unity Editor and Play run configurations, to make it very easy to attach the debugger to the Unity editor.
And best of all, it will work even if you have the class library and the generated solutions open at the same time!
Control when to reloading assemblies
Unity is designed to have a tight feedback loop. Whenever a source file changes, the underlying assemblies are recompiled and reloaded. This works great for immediate feedback, but can be annoying when you’re in play mode – you’re busy play testing a scenario, and a modified file causes everything to reload and lose state. It can be very frustrating.
Unity 2018.2 added an option in the General preferences page to control what happens when scripts change during play mode. We liked it so much, we’ve brought it to earlier versions of Unity. The Rider page in Unity’s preferences dialog will now allow you to prevent assembly reloads during play mode, or reschedule them for after play mode, or to stop play mode straight away and recompile.
This is very useful when used together with Rider’s background refresh, which notifies Unity when a file has changed, causing a recompile. And you’ll also be pleased to hear that this release of Rider continues to fine tune the background refresh, making it a little less aggressive in when it causes a recompile.
Even better, the implementation for the lock assemblies feature came from an external contribution (yes, the Unity support is open source and has up-for-grabs issues!). Congratulations and thanks to Jurjen Biewenga! 🎉
Everything Else
Those are the main new features for editor integration in Rider 2018.2, but that’s not everything. There are also a few more minor updates, although some are no less important. For example:
As you can see, we’ve put a lot of effort into integrating Rider well with Unity, and we’re not done yet. In our next post, we’ll take a look at the new Unity specific inspections in Rider 2018.2.
If you have any suggestions for other features you’d like to see in Rider, please let us know. And in the meantime, please download Rider 2018.2 today, and give it a go (and don’t forget about the 30 day trial version)!
Советы по использованию редактора кода JetBrains Rider в Unity
Что вы узнаете на этой странице: советы по эффективной разработке кода для проектов на Unity с помощью JetBrains Rider. JetBrains Rider — это кроссплатформенная среда разработки скриптов на C# со множеством возможностей для пользователей Unity. Пользуйтесь этими советами, и не забудьте узнать еще больше из доклада на Unite от Мэтта Эллиса из JetBrains.
Используйте сочетание Shift+Shift для поиска по скриптам на C#, включая файлы, классы и символы. Введите в поле поиска все, что вам интересно, и Rider предоставит вам доступные варианты. Вам даже не требуется вводить слова полностью — Rider распознает их по сокращениям.
Для перехода к нужному методу, атрибуту или полю открытого файла можно использовать кнопку Navigate to Member. Сузить область поиска можно вводом искомого текста.
Сочетание Alt+Enter открывает контекстное меню действий для конкретного участка кода, включая исправление ошибок, предлагаемых алгоритмами Rider на основе анализа кода. Например, если нажать сочетание Alt+Enter при курсоре над именем класса, то в меню появится список действий, включая исправление стандартов наименования или открытие общего доступа к классу.
А если вы неправильно ввели имя для метода Invoke, Rider предупредит вас заранее и покажет возможные варианты исправления. При работе в редакторе Unity Rider позволяет избежать изменений, нарушающих работу кода, которых вы бы не заметили до запуска приложения.
Во всплывающем контекстном меню также отображаются точки перехода практически к любой функции Rider. Если вы не можете вспомнить нужное вам сочетание клавиш, то нажмите Alt+Enter, начните вводить название функции, и получите список соответствующих действий.
Функция Refactor This поможет вам провести рефакторинг кода, переместить его в другой файл, переименовать символы как в открытом, так и в других файлах.
Кроме того, меню Alt+Enter можно использовать для генерации функций событий. Это действие доступно для любого класса Unity. Вы получите список всех функций событий, которые доступны для создания в этом конкретном классе.
Rider распознает функцию события, сериализованное поле или класс MonoBehaviour, выделяя их в тексте. Если навести курсор на функцию события, то появится подсказка с описанием этой функции. Введите текст «quick documentation», чтобы получить дополнительную информацию во всплывающем окне, или перейдите по ссылке к полной версии документации.
Меню Navigate to очень полезно для быстрого перемещения по коду Unity, например, к основным или производным классам, а также к примерам использования. Функция также позволяет декомпилировать код Unity на лету, демонстрируя то, что происходит в собственных API Unity.
The Rider debugger shows extra data for Unity objects. For example, when looking at a Scene in the debugger, you see a list of root GameObjects, and each GameObject shows child GameObjects and attached components. ECS Entity objects also show component data.
Rider includes a code-focused profiler that looks at just your scripts; it doesn’t look at any of the other things that are happening inside Unity itself. You can quickly search for types and methods and perform what-if analysis to see if it’s worth optimizing a method.
Переключатель схем позволяет выбирать тему оформления Rider и цветовой гаммы интерфейса.
Эта функция особенно полезна при совместном использовании одного рабочего места — с ее помощью можно менять схему сочетаний клавиш. Например, один программист предпочитает свою схему сочетаний, а второй — свою. Этот инструмент позволяет быстро переключаться между схемами.
Дополнительные рекомендации смотрите в документации Rider for Unity.
Features
You can start with watching this 3-minute video where Matt Ellis gives a short overview of JetBrains Rider features for Unity Development.
Unity Explorer
Modes
By default, when working with a Unity project in Rider, the Explorer window works in the Unity mode showing you all the assets that constitute the project. If you switch the Explorer window to the Solution mode, you will see only the Scripts part of the project.
Packages
Primarily, the Packages node shows you the contents of the Packages folder in the root of your project. This might well only contain a manifest.json file which you can edit in Rider and when saved, Unity will update your project to include the packages you’ve added. More importantly, the Packages node will also show all of the packages referenced in your project. Unity supports a number of different package types, and Rider will show them all. For more details on how Rider works with Unity packages, refer to the blog post.
Control over Unity editor
To reduce the time you spend context switching between Rider and the Unity editor, some of the Unity editor’s functionality is exposed directly in Rider on the Unity toolbar located in the top right corner.
The toolbar allows:
Start Unity : start Unity Editor and open the Unity project that corresponds to the solution opened in Rider.
Start Unity : start Unity Editor with enabled code coverage support and open the Unity project that corresponds to the solution opened in Rider.
Unity Settings. : quickly open the Rider’s Unity Engine settings page.
Show Unity Log Window : open the log viewer.
Switch to Full UI / Switch to Minimized UI : switch between the full Rider UI and the minimized one (all UI elements that are not related to Unity are hidden).
Editor tips
JetBrains Rider marks classes, methods and fields that are implicitly used by Unity directly in the editor.
The UnityEngine.Color and UnityEngine.Color32 colors are highlighted, and hitting Alt+Enter will open the color palette editor to modify the color. Also named colors and Color.HSVToRGB are supported.
Find Usages
In Unity projects, the Find Usages Alt+F7 feature is extended with data pulled from Unity scenes, assets and prefabs. If you search for a class or a method used as an event handler, Rider will show where it is used in Unity files, grouped by type, component name, and parent game objects.
Code Vision
The Code Vision feature also supports Unity. Right in the Rider editor, you can see what classes, methods, fields (including field values set in Unity), and even assets are implicitly used. Code Vision provides navigation to the Unity Editor.
Performance indicators
Event functions
Descriptions for event functions and parameters in Unity based classes are shown in tooltips and Quick Documentation.
Inspections and quick-fixes
Rider shows warnings for unknown scenes, tags, and layers.
When the Solution-wide analysis is enabled, JetBrains Rider understands implicitly used fields and event functions and do not highlight them as not accessed.
Empty event functions are shown as dead code, with a quick-fix to remove them.
Using the SyncVarAttribute inside any class other than NetworkBehaviour is treated as an error.
A quick-fix is suggested to create a serialized field from a usage of an unresolved symbol:
JetBrains Rider ensures that all of your event functions have correct signatures: it highlights incorrect signatures and offers a quick-fix to correct them:
There are also inspections for the [InitializeOnLoad] and [InitializeOnLoadMethod] attributes, ensuring that they have the correct method or constructor signatures, and JetBrains Rider will grey out a redundant [InitializeOnLoad] attribute if the class doesn’t have a static constructor, with a quick-fix to either quickly remove the attribute, or create the constructor.
External annotations
A lot of Unity-specific assemblies are annotated with External annotations to improve code inspection when you make use of these assemblies.
Marking Component.gameObject and Object.name as not-nullable.
Assertions.Assert methods marked as assertion methods to help null-value analysis.
EditorTestsWithLogParser.ExpectLogLineRegex gets regular expression helper functionality.
Support for Unity 2017.2’s modularised UnityEngine assemblies.
JetBrains Rider provides code completion.
[Cg/HLSL] Code completion in Cg/HLSL blocks.
Search everywhere will help you to navigate to symbols inside shader files.
Support for assembly definition files
Live templates
JetBrains Rider offers a couple of Unity-specific live templates:
sprop : a Unity property with a serialized backing field.
sfield : a Unity serialized field.
File templates
JetBrains Rider offers a number of file templates for new C# script, tests, and shader files:
Unity logs
When Rider is connected to the Unity editor, the Unity tool window becomes available. To open the window, select View | Tool Windows | Unity from the main menu or use the Unity-related Actions list on the Unity toolbar.
The Log tab of the Unity tool window brings Unity’s Console into Rider. The tab shows Unity log entries and is updated as events are logged in Unity.
The Output part of the window on the right shows the content of the currently selected log entry. Rider makes the content interactive, so that you can navigate to any source file, class, method or property mentioned in the log entry.
Note that log entries can be filtered by event type: events from play or edit mode, warnings, errors, and messages.
UnityYAMLMerge Support
Rider редактор кода unity
JetBrains Rider — быстрый и мощный редактор C# для Unity, который работает на Windows, Mac и Linux. Непревзойденное количество интеллектуальных механизмов инспекции кода и рефакторинга (более 2500), включенных в Rider, позволяют писать безошибочный код на C# гораздо быстрее.
Легкая интеграция с Unity
В Rider уже встроена поддержка Unity. Когда вы впервые откроете решение Unity, Rider будет автоматически установлен в качестве стандартного редактора для файлов шейдеров и сценариев C#. Впоследствии при двойном щелчке по файлу шейдера или сценарию C# они будут открываться в Rider.
Управление редактором Unity
Благодаря интегрированному механизму двусторонней связи вы можете входить или выходить из режима Play, а также приостанавливать его и продолжать выполнение покадровыми шагами, при этом не покидая Rider. На панели инструментов есть кнопки просмотра игры Play, Pause и Step, которые работают так же, как в редакторе Unity. Небольшая иконка Unity в строке состояния показывает состояние редактора Unity: подключен, обновляет состояние или находится в режиме Play. Любые изменения, внесенные в Rider в режиме Edit, будут сразу же переданы в редактор Unity.
Советы по коду
Rider предоставляет высококлассный механизм анализа кода C# и содержит как специальные инспекции кода для Unity, так и необходимые быстрые исправления.
Удобная отладка Unity
Rider позволяет без проблем осуществлять отладку ваших скриптов C#, когда они выполняются в редакторе Unity. Все необходимые параметры уже настроены, вам нужно лишь нажать сочетание клавиш, команду меню или кнопку Debug на панели инструментов, чтобы подключить отладчик к запущенному редактору Unity. В редакторе можно устанавливать точки останова, исполнять код пошагово, просматривать значения локальных переменных, отслеживать определенные значения, а также вычислять выражения.
С помощью Rider можно выполнять даже отладку кода, для которого нет отладочной информации. Rider автоматически декомпилирует внешние библиотеки, позволяя выполнять отладку декомпилированного кода, входить во вложенные функции, устанавливать точки останова, просматривать и устанавливать локальные и другие переменные.
Запуск тестов Unity
Прямо из Rider можно запускать тесты, взаимодействующие с Unity API и способные выполнять код покадрово. Ну и конечно же, изучать результаты тестов Unity можно так же, как и с обычными тестами, — например, фильтровать по результату и щелкать по трассировкам стека для перемещения по коду.
Журналы консоли Unity
Новое окно инструмента Unity Logs с гиперссылками на трассировки стека позволяет просматривать события, которые регистрируются в консоли редактора Unity. Оно позволяет фильтровать события по категории (ошибка, предупреждение или сообщение), скрывать их в зависимости от того, когда они были зафиксированы (в режиме Play или Edit), а также с легкостью переходить к любому исходному файлу, классу, методу или свойству, упомянутым в записи журнала. Окно Unity Logs автоматически очищается после каждого перехода в режим Play.
Подсветка проблем производительности
Rider позволяет писать более производительный C#-код для Unity. Это достигается путем подсветки ресурсоемких API Unity внутри методов, которые вызываются каждый кадр, таких как Update и корутины. Rider подсвечивает вызовы даже тех методов, которые используют ресурсоемкие API Unity неявным образом.
Помимо этого, Rider оснащен множеством специально предназначенных для Unity инспекций и соответствующих быстрых исправлений. Он способен распознавать паттерны низкопроизводительного кода и может рекомендовать для них автоматические исправления, например использовать перегрузку, кэширование значений или альтернативный API.
Поиск вхождений в файлах Unity
Теперь Find Usages включает в себя сцены, ресурсы и префабы Unity. Если вы ищете класс или метод, используемый в качестве обработчика событий, Rider показывает, где он используется в ваших файлах Unity, группируя такие места по типу, наименованию компонента и родительским игровым объектам. Более того, при двойном щелчке на элементе его вхождения подсвечиваются непосредственно в редакторе Unity.
Теперь при извлечении этой информации из файлов Unity Rider корректно подсвечивает методы обработчика событий как неявно используемые. Подсветка неявного использования преобразуется в ссылки Code Vision, что позволяет вам сразу видеть, какие классы, методы и поля неявно используются Unity. При нажатии на такую ссылку будут найдены все вхождения элемента, в том числе в файлах Unity.
Поддержка шейдеров
Rider теперь также поддерживает файлы .shader, обеспечивая подсветку синтаксиса, сворачивание кода, выделение парных скобок и многое другое. Подсвечиваются синтаксические ошибки в разделах ShaderLab, комментарии типа todo упорядочиваются в окне To Do Explorer, подсветкой также отмечаются цветовые свойства, которые можно редактировать с помощью специального инструмента выбора цвета. Автозаполнение простых слов доступно в рамках всего файла, в том числе в блоках кода Cg/HLSL.
Просмотр документации Unity
Бесплатная пробная версия на 30 дней
Клиенты
«Наличие подходящего инструментария исключительно важно для сохранения конкурентоспособности на любом рынке — и особенно в сфере игр. Каждый разработчик в Yakuto имеет подписку на JetBrains Toolbox — важность этого пакета для продуктивной работы, с нашей точки зрения, невозможно переоценить. Основная наша работа ведется в C# на компьютерах Mac. Из-за этого раньше нам требовалась виртуальная машина с ReSharper, но благодаря Rider мы работаем с одной ОС в native-режиме, и это просто здорово. Отладка Unity стала бесшовным процессом, а расширения позволили установить важную контекстуальную связь с Unity. Будучи опытным пользователем ReSharper, я чувствую себя в Rider как дома: рефакторинг, глобальный анализ решения, инструменты запуска тестов — все это у меня под рукой. Мы даже не можем себе представить, как вели бы разработку на C# без Rider».
Джеймс Грэттон
Технический директор, Yakuto
«Rider быстро стала единственной IDE, которую хочется использовать для любых задач разработки на UE4 или Unity. Я экономлю очень много времени благодаря понятным рабочим процессам и доволен интеграцией с P4. Когда руководители видят, как быстро мы движемся от постановки задач к решению, они приходят в восторг от продукта. Rider устраняет все затруднения, мешающие нам делать то, что мы умеем лучше всего, — писать код».
«Во всех смыслах лучшая IDE для Unity под Mac. Беспрецедентные возможности отладки и рефакторинга».
Эрин Кинен
Инженер-программист, компания-производитель мобильных игр N3twork