Object с editor windows

Is there a way to use serializedObject in EditorWindow script?

I have a script with a List :

And when using only Editor script not EditorWindow I could do :

But now I want to do it in a EditorWindow script :

But I’m getting error on the line inside the OnGUI :

The error is on the serializedObject :

The name ‘serializedObject’ does not exist in the current context

If I’m changing it to SerializedObject I’m getting error :

An object reference is required for the non-static field, method, or property ‘SerializedObject.FindProperty(string)’

I tried to change the _conversations to be static but it didn’t help.

I also tried to make :

But not sure how to work with it. Why in the Editor script it was working fine but in the EditorWindow it’s not ?

1 Answer 1

The difference is that Editor

as you can see the is clearly related to one certain type in

further, and more important, it is the inspector for one certain instance of that type attached to the currently selected GameObject. Therefore you can acccess the serializedObject instance of that MonoBehaviour (or ScriptableObject )

A SerializedObject representing the object or objects being inspected.

On the other side EditorWindow is not related to a certain type nor to a certain instance or GameObject but is just a window that will be opened. You can say it lives in a kind of static environment (instead of the instanced one like the Editor ).

Therefore there simply is no serializedObject it would be related to => It doesn’t have such a property.

Using SerializedObject ofcourse doesn’t work as this is a type not an instance and the method FindProperty is not static but requires an instance as the error message tries to tell you.

I don’t want to sound bad but if that is is something you don’t understand yet than you should immediately stop worrying about EditorScripting and get some refreshments in basic c# coding and/or object-oriented programming in general.

if you somehow can get a reference to one certain instance of Test .

You could do that for example using FindObjectOfType

To get the first active and enabled Test instance from the current Scene.

to get the first encounter of Test from the selected objects in the scene hierarchy window.

As alternative you could open that EditorWindow from the Inspector of Test instead of openening it from the static menu bar and pass in the MonoBehaviour reference. (Passing in the serializedObject directly would only work if the Inspector stays opened since the serializedObject instance is probably destroyed along with the TestEditor when the GameObject is not selected anymore)

And received and store the reference in

Note: Typed on smartphone so no warranty but I hope the idea gets clear

Расширение редактора Unity через Editor Window, Scriptable Object и Custom Editor

Всем привет! Меня зовут Гриша, и я основатель CGDevs. Сегодня хочется поговорить про расширения редактора и рассказать про один из моих проектов, который я решил выложить в OpenSource.

Юнити — прекрасный инструмент, но в нём есть небольшая проблема. Новичку, чтобы сделать простую комнату (коробку с окнами), необходимо либо осваивать 3д моделирование, либо пытаться что-то собрать из квадов. Недавно стал полностью бесплатным ProBuilder, но это так же упрощённый пакет 3д моделирования. Хотелось простой инструмент, который позволит быстро создавать окружения вроде комнат со окнами и правильными UV при этом. Достаточно давно я разработал один плагин для Unity, который позволяет быстро прототипировать окружения вроде квартир и комнат с помощью 2д чертежа, и сейчас решил выложить его в OpenSource. На его примере мы разберём, каким образом можно расширять редактор и какие инструменты для этого существуют. Если вам интересно – добро пожаловать под кат. Ссылка на проект в конце, как всегда, прилагается.

Unity3d обладает достаточно широким инструментарием для расширения возможностей редактора. Благодаря таким классам, как EditorWindow, а также функционалу Custom Inspector, Property Drawer и TreeView (+ скоро должны появиться UIElements) поверх юнити легко надстраивать свои фреймворки разной степени сложности.

Сегодня мы поговорим про один из подходов, который я использовал при разработке своего решения и про пару интересных задач, с которыми пришлось столкнуться.

В основе решения лежит использование трёх классов, таких как EditorWindow (все дополнительные окна), ScriptableObject (хранение данных) и CustomEditor (дополнительный функционал инспектора для Scriptable Object).

При разработке расширений редактора важно стараться придерживаться принципа, что расширением будут пользоваться Unity разработчики, поэтому интерфейсы должны быть понятными, нативными и вписанными в воркфлоу Unity.

Поговорим про интересные задачи.

Для того, чтобы нам прототипировать что-то, в первую очередь нам надо научиться рисовать чертежи, из которых мы будем генерировать наше окружение. Для этого нам необходимо специальное окно EditorWindow, в котором мы будем отображать все чертежи. В принципе можно было бы рисовать и в SceneView, но изначальная идея заключалось в том, что при доработке решения может захотеться открывать несколько чертежей одновременно. В целом в юнити создать отдельное окно — это достаточно простая задача. Об этом можно почитать в мануалах Unity. А вот чертёжная сетка – задача поинтереснее. На эту тему есть несколько проблем.

Читайте также:  Свой jabber сервер linux

В Юнити несколько стилей, которые влияют на расцветку окон

Дело в том, что большинство использующих Pro версию Unity используют тёмную тему, а во бесплатной версии доступна только светлая. Тем не менее, цвета, которые используются в редакторе чертежей, не должны сливаться с фоном. Тут можно придумать два решения. Сложное – сделать свою версию стилей, проверять её и изменять палитру под версию юнити. И простое — залить фон окна определённым цветом. При разработке было решено использовать простой путь. Пример того, как это можно сделать — вызвать в OnGUI методе такой код.

В сущности мы просто отрисовали текстуру цвета BgColor во всё окно.

Отрисовка и перемещение сетки

Вот тут открылось сразу несколько проблем. Первое, необходимо было ввести свою систему координат. Дело в том, что для корректной и удобной работы нам надо пересчитывать GUI координаты окна в координаты грида. Для этого были реализованы два метода преобразования (в сущности, это две расписанные TRS матрицы)

где _ParentWindow — это окно в котором мы собираемся рисовать сетку, _Offset — текущая позиция грида, а _Zoom — степень приближения.

Во-вторых, для отрисовки линий нам потребуется метод Handles.DrawLine. Класс Handles имеет внутри себя много полезных методов для отрисовки простой графики в окнах редактора, инспекторе или SceneView. На момент разработки плагина (Unity 5.5) Handles.DrawLine – аллоцировало память и в целом работало достаточно медленно. По этой причине количество возможных линий для отрисовки было ограничено константой CELLS_IN_LINE_COUNT , а также сделан “LOD level” при зуме, чтобы добиться приемлемого fps в редакторе.

Для грида почти всё готово. Его движение описывается очень просто. _Offset – это в сущности нынешняя позиция «камеры».

В самом проекте можно ознакомиться с кодом окна в общем и посмотреть, каким образом на окно можно добавить кнопки.

Едем дальше. Помимо отдельного окна для отрисовки чертежей нам надо как-то хранить сами чертежи. Для этого отлично подходит внутренний механизм сериализации Unity – Scriptable Object. По сути, он позволяет хранить описанные классы в виде ассетов в проекте, что очень удобно и нативно для многих юнити разработчиков. Для примера, часть класса Apartment, которая отвечает за хранение информации о планировке в целом

В редакторе он выглядит в текущей версии так:

Тут, конечно, уже применён CustomEditor, но тем не менее можно заметить, что такие параметры, как _Dimensions, Height, IsGenerateOutside, OutsideMaterial и PlanImage отображаются в редакторе.

Все публичные поля и поля, помеченные [SerializeField] – сериализуются (то есть сохраняются в файле в данном случае). Это сильно помогает при необходимости сохранять чертежи, но при работе со ScriptableObject, да и всеми ресурсами редактора необходимо помнить, что лучше для сохранения состояния файлов вызывать метод AssetDatabase.SaveAssets(). Иначе изменения не сохранятся. Если вы только руками не сохраните проект.

Теперь частично разберём класс ApartmentCustomInspector, и то как он работает.

CustomEditor – это очень мощный инструмент, позволяющий решать элегантно множество типовых задач по расширению редактора. В паре с ScriptableObject он позволяет делать простые, удобные и понятные расширения редактора. Этот класс немного сложнее простого добавления кнопок, так как в исходном классе можно заметить, что сериализуется поле [SerializeField] private List _Rooms. Отображение его в инспекторе, во-первых, ни к чему, во-вторых – это может вести к непредвиденным багам и состояниям чертежа. За отрисовку инспектора отвечает метод OnInspectorGUI, и, если вам необходимо просто добавить кнопки, то вы можете вызвать в нём метод DrawDefaultInspector() и все поля будут отрисованы.

Тут же вручную отрисовываются необходимые поля и кнопки. Класс EditorGUILayout в себе имеет много реализаций для самых разных видов полей, поддерживаемых юнити. Но отрисовка кнопок в Unity реализована в классе GUILayout. Как в данном случае работает обработка нажатия кнопок. OnInspectorGUI – отрабатывает на каждое событие пользовательского ввода мышью (перемещение мыши, нажатие клавиш мыши внутри окна редактора и т.п.) Если пользователь сделал клик мышью в баундинг боксе кнопки, то метод возвращает true и отрабатывают методы, которые находятся внутри описанного вами if’a. Для примера:

При нажатии на кнопку Generate Mesh вызывается статический метод, отвечающий за генерацию меша конкретной планировки.

Кроме этих базовых механизмов, используемых при расширении редактора Unity, хотелось бы отдельно отметить очень простой и очень удобный инструмент, про который почему-то многие забывают – Selection. Selection – это статический класс, позволяющий вам выделять в инспекторе и ProjectView необходимые объекты.

Для того, чтобы выбрать какой-то объект, вам просто необходимо написать Selection.activeObject = MyAwesomeUnityObject. И самое прекрасное, что он работает со ScriptableObject. В данном проекте он отвечает за выбор чертежа и комнат в окне с чертежами.

Спасибо за внимание! Надеюсь, статья и проект будут полезны вам, и вы почерпнёте для себя что-то новое в одном из подходов расширения редактора Unity. И как всегда – ссылка на GitHub проект, где можно посмотреть проект целиком. Он пока немного сыроват, но тем не менее уже позволяет делать планировки в 2д просто и быстро.

Читайте также:  Mac experience on windows

15 Best C++ IDE: Free Windows Editor | Compiler | 2021

C++ is a general-purpose object-oriented programming language developed by Bjarne Stroustrup. It contains the features of C programming language as well as Simula67 (a first object Oriented language).

There are many Integrated Development Environments (IDE) that provide readymade code templates to write C++ programs. These tools automatically adjust the indent and format of code. IDE’s help to code your application in less amount of time.

Following is a handpicked list of Best C++ IDE, with their popular features and website links. The list contains both open source(free) and commercial(paid) software.

Best C++ Editor and C++ IDE for Windows/Mac OS

Name Link
C++Builder https://www.embarcadero.com/products/
Kite https://www.kite.com/get-kite/
Visual Studio Code https://code.visualstudio.com/
Eclipse https://www.eclipse.org/ide/
Codelite https://codelite.org/

1) C++Builder

C++Builder is the full-featured C++ IDE for building Windows apps five times faster than with other IDEs. That’s because of the rich visual frameworks and expansive libraries. Prototyping, developing and shipping are easy with C++Builder.

Features:

  • It supports you through the full development lifecycle to deliver a single source codebase that you simply recompile and redeploy.
  • Featuring an enhanced Clang-based compiler, Dinkumware STL, and packages like Boost and SDL2 in C++Builder’s package manager, and many more
  • Integrate with continuous build configurations quickly with MSBuild, CMake, and Ninja support either as a lone developer or as part of a team.
  • Connect natively to almost 20 databases like MariaDB, Oracle, SQL Server, Postgres and more with FireDAC’s high speed direct access.
  • includes the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.

2) Kite

Kite is IDE for C++ that automatically completes multiple line codes. This editor supports more than 16 languages. It helps you to code faster with no hassle.

Price: Free

Features:

  • It offers Java documentation.
  • This editor provides a function signature as you type.
  • You will get a tooltip on mouse hover.
  • Provides support in email.
  • Uses machine learning models for Java language.

3) Visual Studio Code

Visual Studio Code is an open-source code editor developed by Microsoft. It is one of the best c++ ide which provides smart code completion based on variable types, essential modules, and function definitions.

Features:

  • It is one of the best c++ ide for windows that can work with Git version control system.
  • You can debug code easily using this c++ programming software.
  • It is one of the free c++ ide which supports numerous extensions for including new languages, themes, and more.
  • Visual Studio Code can be used on Windows and Mac operating systems.
  • It provides best c++ compiler and you can control multiple versions of one program with ease.

4) Eclipse

Eclipse is a website development tool for C++. It highlights the syntax you have written. This tool enables you to easily debug the program.

Features:

  • This online ide tool automatically validates syntax.
  • It supports parser ( a part of the compiler).
  • Eclipse enables you to manage the project remotely.
  • It can be used on platforms like Windows, Linux, and OS X.
  • This c++ programming software tool generates Makefile that contains instructions for how to build your C++ program.
  • It provides readymade code templates.

5) Codelite

CodeLite is an open source tool for writing programs in C++. It is one of the best c++ ide that supports code refactoring. This app highlights the syntax. You can use it on Windows and Mac operating systems.

Features:

  • Codelite can be integrated with Cscope integration (text-based interface to search a code).
  • You can customize syntax colors.
  • This online ide tool helps you to find files effortlessly using a tree view.
  • It is one of the best ide for c programming and c++ that has a command palate that holds functionality like sorting, changing the syntax, etc.

6) Atom

Atom is a simple editor for writing C++ program. It can be customized to do anything without modifying a config file.

Features:

  • It is one of the best editor for c++ which has an integrated package manager.
  • This c++ editor tool allows cross-platform editing
  • You can find, preview, and replace text typed in a file or across the entire project.
  • It offers a command palette that contains items that are used repeatedly.

7) CLion

CLion is a tool developed by Jetbrains. It helps you to quickly solve errors in the program. This IDE for c++ enables you to analyze the performance of your application with no hassle.

Features:

  • You can effortlessly run and debug your program.
  • It helps you to test individual units of source code.
  • You can integrate CLion with CVS (Concurrent Versions System) and TFS (Team Foundation Server).
  • You can customize the editor the way you like.
  • This software helps you to manage your project and code effectively.
  • It automatically set formatting while you write code.

8) Emacs

Emacs is a Unix based tool that provides a highly customizable feature. It is one of the best c++ ide for mac that supports syntax coloring. You can use this software on GNU, Windows, or mac operating system.

Features:

  • It is one of the best c++ editor that supports Unicode for numerous human scripts.
  • It provides a packaging system for installing and downloading numerous extensions.
  • You can customize this app using the Emacs Lisp code.
  • Emacs offers complete built-in documentation.
  • This app offers a tutorial for new users.

9) Notepad++

Notepad++ is a code editor that can be used with Windows. This c++ ide tool highlights syntax and keyword. It helps you to work with multiple open files in a single window.

Features:

  • It highlights brackets written in C++ program.
  • You can zoom in or zoom out the screen.
  • Macro (Automatic expandable instruction) recording and playback is possible.
  • GUI is customizable.
  • It is one of the best editor for c++ which supports the multi-language environment.

10) Netbeans

NetBeans is an integrated development environment for writing C++ programs. It is one of the best c++ ide for windows that has a project window that shows a list of projects currently exists.

Features:

  • You can set exception, variable, function breakpoints, etc. and view them in the Breakpoints window.
  • It automatically adjusts indent and format the code.
  • You can easily see the structure of the C++ class.
  • This tool highlights variables and keywords in your C++ program.
  • It automatically completes the brackets.
  • Netbeans is one of the free c++ ide that offers readymade templates for writing C++ code.

11) Codeblocks

Codeblocks is open source IDE for writing programs in C++. It is one of the best c++ ide for mac that supports GCC (GNU Compiler Collection), Visual C++, etc. You can use this app on Windows, Linux, and macOS.

Features:

  • This c++ editor provides one of the best c++ compiler and workspace to easily combine more than one project.
  • Codeblocks has a feature that automatically completes the code.
  • You can build more than one project simultaneously.
  • It allows you to write full breakpoint conditions (stop the execution of code if the expression is true).
  • You can quickly switch between multiple programs.
  • It is one of the free c++ ide app which provides a tabbed interface.

12) Cevelop

Cevelop is one of the best C++ IDE for developers. It enables you to migrate a variable declaration to the new syntax. It is one of the best ide for c++ which helps you to detect uninitialized variables.

Features:

  • It makes code more readable by using global namespace (a name representing one entity).
  • This software has a template view that displays detailed template information.
  • It helps you to analyze and optimize the code.
  • Cevelop supports Ctylechecker plugin to find mistakes in the program.

13) Kdevelop

Kdevelop is an open-source integrated development environment for C++ developers. You can use this software on Windows, Linux, macOS, Solaris, and more.

Features:

  • It is one of the best ide for c programming and c++ which provides language support for OpenCL (Open Computing Language).
  • You can jump to the declaration /definition code.
  • Kdevelop helps you to quickly search for any function or class.
  • It can highlight code having different meanings and usage.
  • This c++ editor tool provides one of the best c++ compiler and can highlight the occurrence of same variable in a particular color.
  • You can assign shortcuts to every action in this tool.
  • This tool supports version control systems like Subversion, CVS, Perforce, and more.

14) SlickEdit

SlickEdit is a cross-platform IDE for writing in the program. It is one of the best c++ editor which supports more than 60 languages. This ide for c++ can load large files quickly.

Features:

  • You can customize menu items.
  • It enables you to open a file without typing a path.
  • Easy to integrate Subversion, CVS, etc.
  • You can expand a common block structure.
  • SlickEdit can automatically formats code when pasted.
  • You can create multi-platform GUI dialogue boxes.
  • This c++ editor software automatically saves the file after a period of inactivity.

15) Graviton

Graviton is a user-friendly editor that helps you to write and manage the C++ code effectively. It is one of the best c++ editor which is available in English, Spanish, and many other languages.

Features:

  • It is compatible with macOS, Windows, and Linux platforms.
  • Graviton keeps your data on your PC instead of server.
  • You can hide unwanted code in the editor.
  • This tool has an explorer panel that helps you to select files or folders for copying, moving, or deleting.

❓ What is the IDE in C++?

C++ is a general-purpose, object-oriented programming language developed by Bjarne Stroustrup. An IDE generally contains a source code editor, a debugger, build automation tools. IDE’s help to code your application in less amount of time.

Читайте также:  Dvc100 драйвер windows 10 x64
Оцените статью