This page has been translated automatically.
Видеоуроки
Interface
Essentials
Advanced
Подсказки и советы
Основы
Программирование на C#
Рендеринг
Professional (SIM)
Принципы работы
Свойства (properties)
Рендер
Физика
Редактор UnigineEditor
Обзор интерфейса
Работа с ассетами
Настройки и предпочтения
Работа с проектами
Настройка параметров ноды
Setting Up Materials
Настройка свойств
Освещение
Landscape Tool
Sandworm
Использование инструментов редактора для конкретных задач
Расширение функционала редактора
Встроенные объекты
Ноды (Nodes)
Объекты (Objects)
Эффекты
Декали
Источники света
Geodetics
World Nodes
Звуковые объекты
Объекты поиска пути
Players
Программирование
Основы
Настройка среды разработки
Примеры использования
C++
C#
UnigineScript
UUSL (Unified UNIGINE Shader Language)
Плагины
Форматы файлов
Materials and Shaders
Rebuilding the Engine Tools
GUI
Двойная точность координат
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Работа с контентом
Оптимизация контента
Материалы
Визуальный редактор материалов
Сэмплы материалов
Material Nodes Library
Miscellaneous
Input
Math
Matrix
Textures
Art Samples
Tutorials
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Система компонентов C #

Component System enables you to implement your application's logic via a set of building blocks — components, and assign these blocks to nodes, giving them additional functionality. By combining these small and simple blocks you can create a very sophisticated logic system. Система компонентов позволяет реализовать логику вашего приложения с помощью набора строительных блоков - компонентов и назначать эти блоки узлам, предоставляя им дополнительную функциональность. Комбинируя эти маленькие и простые блоки, вы можете создать очень сложную логическую систему.

A logic component integrates a node and a C# class, containing logic implementation (actions to be performed), defining a set of additional parameters to be used. Логический компонент объединяет узел и класс C #, содержащий логическую реализацию (действия, которые должны быть выполнены), определяющий набор дополнительных параметров, которые будут использоваться.

Components assigned to a node Компоненты, назначенные узлу

Components give you more flexibility in implementing your logic, enabling you to: Компоненты дают вам больше гибкости в реализации вашей логики, позволяя:

  • Control which parts of code (implemented as component methods) are to be executed, and which of them are not. Управляйте тем, какие части кода (реализованные как методы компонентов) должны выполняться, а какие нет.
  • Control execution order of these parts of code. Контролировать порядок выполнения этих частей кода.
  • Repeatedly use parts of code, written once, for as many objects as you need, with no modifications required. If you want to change your code, you modify a single source (similar to NodeReferences, if we talk about content). Неоднократно используйте части кода, написанные один раз, для любого количества объектов без каких-либо изменений. Если вы хотите изменить свой код, вы изменяете единственный источник (аналогично NodeReferences , если мы говорим о контенте).
  • Combine certain parts of code to be executed for certain nodes. Build a very sophisticated system from numerous small and simple blocks (like you would use a NodeReference to build a large complex structure using many simple nodes). Объедините определенные части кода, которые будут выполняться для определенных узлов. Создайте очень сложную систему из множества маленьких и простых блоков (например, вы использовали бы NodeReference для создания большой сложной структуры с использованием множества простых узлов).

Before starting coding, you should install required software. Перед началом кодирования вы должны установить необходимое программное обеспечение .

See AlsoСмотрите также#

RequirementsТребования#

Proper workflow for programming and building .NET-based projects implies a set of requirements: Правильный рабочий процесс для программирования и создания проектов на основе .NET подразумевает ряд требований:

  • .NET 5 SDK (for both Windows and Linux) .NET 5 SDK (для Windows и Linux)
  • an IDE or a text editor. Compatibility of different IDEs with the following .NET versions is checked:
    IDE Supported .NET version
    MS Visual Studio Code MS Visual Studio Code 5.0.x 5.0.x
    MS Visual Studio 2019 MS Visual Studio 2019 5.0.x 5.0.x
    Примечание
    Visual Studio Code is the recommended option.Visual Studio Code is the recommended option.
    MS Visual Studio Code 5.0.x MS Visual Studio 2019 5.0.x Visual Studio Code is the recommended option.
    IDE или текстовый редактор. Проверяется совместимость различных IDE со следующими версиями .NET:
    IDE Supported .NET version
    MS Visual Studio Code MS Visual Studio Code 5.0.x 5.0.x
    MS Visual Studio 2019 MS Visual Studio 2019 5.0.x 5.0.x
    Примечание
    Visual Studio Code is the recommended option. Visual Studio Code - рекомендуемый вариант.

If you work with MS Visual Studio Code, install the C# extension for Visual Studio Code powered by OmniSharp when first opening the component. Если вы работаете с MS Visual Studio Code, установите расширение C # для Visual Studio Code с питанием от OmniSharp при первом открытии компонента.

In case of any issues with .NET, check the Troubleshooting section on .NET issues. В случае возникновения каких-либо проблем с .NET, проверьте раздел "Устранение неполадок" в проблемах .NET.

Creating a ComponentСоздание компонента#

Components are created using the Editor. Open the Asset Browser and choose Create -> Create C# Component. Компоненты создаются с помощью Editor . Откройте Asset Browser и выберите Create -> Create C# Component.

Specify a name for the component in the prompt dialog, after which a C# script asset file with the corresponding name will be created in the current directory of the Asset Browser. Укажите имя для компонента в диалоговом окне подсказки, после чего в текущем каталоге браузера ресурсов будет создан файл ресурсов сценария C # с соответствующим именем.

Double-click the new script asset to edit the component logic in the default IDE. Дважды щелкните новый ресурс сценария, чтобы изменить логику компонента в IDE по умолчанию.

Внимание
Do not create components in the mount point. Не создавайте компоненты в точке монтирования .

Renaming ComponentsПереименование компонентов#

Ideally, you name things properly from the start. The name should be clean and reflective of what it does. But, sometimes things do change, and suddenly you realize that your component's name has to be changed. Since 2.11 it's not a big deal. Actually, there are two ways you can do it: В идеале, вы с самого начала называете вещи правильно. Название должно быть чистым и отражать то, что оно делает. Но иногда что-то действительно меняется, и внезапно вы понимаете, что нужно изменить имя вашего компонента. Начиная с 2.11 это не проблема. На самом деле, это можно сделать двумя способами:

  • Renaming your cs-asset in the Asset Browser. Component class and associated property will be renamed automatically. The only thing you have to do in this case is to replace all references to your component class in your source code with new ones in your preferred IDE via Find&Replace. Переименование вашего cs-ресурса в браузере ресурсов . Класс компонента и связанное с ним свойство будут переименованы автоматически. Единственное, что вам нужно сделать в этом случае, - это заменить все ссылки на ваш класс компонента в исходном коде на новые в вашей предпочтительной среде IDE через Find&Replace.
  • Using refactoring tools of your IDE (e.g., Rename symbol in VS Code or Edit -> Refactor -> Rename in Visual Studio). After renaming simply open UnigineEditor - the corresponding cs-asset and associated property will be renamed automatically keeping all references. Please be aware that in this case the name of the cs-file containing implementation of your component will change and the file will be removed from the project by your IDE as a missing one. So, you'll have to add the renamed file back to the project in the IDE. Использование инструментов рефакторинга вашей IDE (например, Rename symbol в VS Code или Edit -> Refactor -> Rename в Visual Studio). После переименования просто откройте UnigineEditor - соответствующий cs-актив и связанное с ним свойство будут переименованы автоматически с сохранением всех ссылок. Имейте в виду, что в этом случае имя cs-файла, содержащего реализацию вашего компонента, изменится, и файл будет удален из проекта вашей IDE как отсутствующий. Итак, вам придется добавить переименованный файл обратно в проект в среде IDE.

Structure of a ComponentСтруктура компонента#

Essentially components are C# classes inherited from the base Component class. По сути, компоненты - это классы C #, унаследованные от базового класса Component.

The work of the C# Component System is based on properties. When you create a new component, it is automatically registered in the Component System and an internal runtime property is created and associated with the component via a GUID. The following Component class attribute is required for proper work of the component. Работа системы компонентов C # основана на properties . Когда вы создаете новый компонент, он автоматически регистрируется в Component System и создается внутреннее свойство runtime и связан с компонентом через GUID. Для правильной работы компонента необходим следующий атрибут класса Component.

Исходный код (C#)
[Component(PropertyGuid = "2ae011355ed7f110a202912faa000cc22276e539")]
Внимание
The value of the Component attribute must not be changed. Значение атрибута Component нельзя изменять.

C# components are listed in the Properties hierarchy, initially they are inherited from the base C# Components property. Компоненты C # перечислены в иерархии Properties, изначально они унаследованы от базового свойства C# Components.

Примечание
Generic auto inheritance of components is not supported, you can derive logic implementation from an arbitrary component manually by inheriting its class from the class of the parent component. Общее автоматическое наследование компонентов не поддерживается, вы можете получить логическую реализацию из произвольного компонента вручную, унаследовав его класс от класса родительского компонента.

Simple InheritanceПростое наследование#

Suppose you have a component implementing certain functionality, and you need a certain number of subcomponents having exactly the same functionality, but different parameter values. This situation is typical when implementing quality presets or configurations of controls. Just inherit a property from the basiс component in the UnigineEditor for each preset and tweak necessary parameter values. After that you can assign these inherited properties to nodes, thus attaching to them the logic of the basic component with parameter values taken from inherited properties. No excessive copy-pasting, no redundant code. Предположим, у вас есть компонент, реализующий определенную функциональность, и вам нужно определенное количество подкомпонентов, имеющих точно такие же функциональные возможности, но разные значения параметров. Такая ситуация типична при реализации предварительных настроек качества или конфигураций элементов управления. Просто унаследуйте свойство от базового компонента в UnigineEditor для каждого пресета и настройте необходимые значения параметров. После этого вы можете назначать эти унаследованные свойства узлам, таким образом присоединяя к ним логику базового компонента со значениями параметров, взятыми из унаследованных свойств. Без излишнего копирования, без избыточного кода.

LogicЛогика#

Logic of components is implemented via a set of methods, that are called by the corresponding functions of the world script: Логика компонентов реализована с помощью набора методов, которые вызываются соответствующими функциями скрипта world :

  • Init() — create and initialize all necessary resources. Init() - создать и инициализировать все необходимые ресурсы.
  • UpdateAsyncThread() — specify all logic functions you want to be called every frame independent of the rendering thread.
    Примечание
    This method does not have protection locks, so it is not recommended to modify other components inside this method, unless you are absolutely sure, that these components won't be modified or removed elsewhere.This method does not have protection locks, so it is not recommended to modify other components inside this method, unless you are absolutely sure, that these components won't be modified or removed elsewhere.
    This method does not have protection locks, so it is not recommended to modify other components inside this method, unless you are absolutely sure, that these components won't be modified or removed elsewhere.
    UpdateAsyncThread() - укажите все логические функции, которые вы хотите вызывать в каждом кадре независимо от потока рендеринга.
    Примечание
    This method does not have protection locks, so it is not recommended to modify other components inside this method, unless you are absolutely sure, that these components won't be modified or removed elsewhere. Этот метод не имеет защитных блокировок, поэтому не рекомендуется изменять другие компоненты внутри этого метода, если вы не уверены, что эти компоненты не будут изменены или удалены где-либо еще.
  • UpdateSyncThread() — specify all parallel logic functions you want to be executed before the Update(). This method can be used to perform some heavy resource-consuming calculations such as pathfinding, generation of procedural textures and so on.
    Примечание
    This method should be used to call only the API methods related to the current node: the node itself, its materials and properties.This method should be used to call only the API methods related to the current node: the node itself, its materials and properties.
    This method should be used to call only the API methods related to the current node: the node itself, its materials and properties.
    UpdateSyncThread() - укажите все функции параллельной логики, которые вы хотите выполнить перед Update (). Этот метод можно использовать для выполнения некоторых ресурсоемких вычислений, таких как поиск пути, генерация процедурных текстур и т.д.
    Примечание
    This method should be used to call only the API methods related to the current node: the node itself, its materials and properties. Этот метод следует использовать для вызова только методов API, относящихся к текущему узлу: самому узлу, его материалам и свойствам.
  • Update() — specify all logic functions you want to be called every frame. Update() - укажите все логические функции, которые вы хотите вызывать в каждом кадре.
  • PostUpdate() — correct behavior according to the updated node states in the same frame. PostUpdate() - правильное поведение в соответствии с обновленными состояниями узлов в том же кадре.
  • UpdatePhysics() — simulate physics: perform continuous operations (pushing a car forward depending on current motor's RPM, simulating a wind blowing constantly, perform immediate collision response, etc.). UpdatePhysics() - имитировать физику: выполнять непрерывные операции (толкать автомобиль вперед в зависимости от оборотов двигателя, имитировать постоянно дующий ветер, выполнять немедленную реакцию на столкновение и т. д.).
  • Swap() — operate with the results of the updateAsyncThread() method — all other methods (threads) have already been performed and are idle. After this function, only two actions occur:
    • All objects that are queued for deletion are deleted.All objects that are queued for deletion are deleted.
    • Profiler is updated.Profiler is updated.
    All objects that are queued for deletion are deleted.Profiler is updated.
    Swap() - работать с результатами метода updateAsyncThread() - все остальные методы (потоки) уже выполнены и простаивают. После этой функции происходит только два действия:
    • All objects that are queued for deletion are deleted. Все объекты, поставленные в очередь на удаление, удаляются.
    • Profiler is updated. Profiler is updated.
  • Shutdown() — perform cleanup on component shutdown. Shutdown() - выполнять очистку при выключении компонента.
Примечание
You can set multiple methods for each stage (e.g. multiple Update() methods or just a single Init()). Вы можете установить несколько методов для каждого этапа (например, несколько методов Update() или только один Init () ).
Внимание
The UpdateAsyncThread() and UpdateSyncThread() methods allow calling only thread-safe engine functions. Методы UpdateAsyncThread(), UpdateSyncThread() и UpdatePhysics() позволяют вызывать только потокобезопасные функции движка.

ParametersПараметры#

Components can have parameters that are editable in the Parameters window. Компоненты могут иметь параметры, которые можно редактировать в окне Parameters.

The following entities have auto-generated UI in the Editor based on the data type and the set of attributes: Следующие объекты имеют автоматически сгенерированный пользовательский интерфейс в редакторе на основе типа данных и набора атрибутов:

  • public fields of the component class public поля класса компонента
  • any private and protected fields of the supported types with the [ShowInEditor] option enabled любые поля private и protected поддерживаемых типов с опцией [ShowInEditor]
Исходный код (C#)
public int public_field;

private int private_field;

[ShowInEditor]
private float private_editable_field;

[HideInEditor]
public float public_hidden_field;

Parameters and their attributes can be declared for editor widgets. Параметры и их атрибуты могут быть объявлены для виджетов редактора.

Refer to the Component class for more details on supported parameter types and attributes. Дополнительные сведения о поддерживаемых типах параметров и атрибутах см. в классе Component.

Applying Component Logic to a NodeПрименение логики компонентов к узлу#

Logic implementation described in a component is active at run time only if the component is assigned to a node and both node and component are enabled. Логическая реализация, описанная в компоненте, активна во время выполнения, только если компонент назначен узлу, и оба узла и компонент включены.

There are several ways of applying a component to a node: Есть несколько способов применения компонента к узлу:

  • Select a node, click Add New Property and type the name of a *.cs asset in the Node Properties section of the Node tab. You can do it by dragging the *.cs asset there from the Asset Browser window as well.

    Dragging to the node in the Editor Viewport is also supported.Dragging to the node in the Editor Viewport is also supported.

    Dragging to the node in the Editor Viewport is also supported.
    Выберите узел, щелкните Add New Property и введите имя актива *.cs в разделе Node Properties вкладки Node. Вы можете сделать это, перетащив туда ресурс *.cs из окна Asset Browser.

    Dragging to the node in the Editor Viewport is also supported. Также поддерживается перетаскивание на узел в окне просмотра редактора.

  • Add a component to a node via code by using the AddComponent<T>(Node node) and Node's AddComponent<T>() functions. Добавьте компонент к узлу с помощью кода, используя функции AddComponent<T>(Node node) и AddComponent<T>() узла.
Исходный код (C#)
NewComponent component = AddComponent<NewComponent>(node);

NewComponent component = node.AddComponent<NewComponent>();

The logic of a certain component is active only when the component and the corresponding node are enabled. Thus, you can enable/disable logic of each particular component at run time when necessary. Логика определенного компонента активна только тогда, когда компонент и соответствующий узел включены. Таким образом, при необходимости вы можете включать / отключать логику каждого конкретного компонента во время выполнения.

You can assign several components to a single node. The sequence, in which the logic of components is executed, is determined by the order value specified for the corresponding methods (if order values are the same or not specified, the sequence is indeterminable). Вы можете назначить несколько компонентов одному узлу. Последовательность, в которой выполняется логика компонентов, определяется значением order, указанным для соответствующих методов (если значения order совпадают или не указаны, последовательность неопределима).

Components can interact with other components and nodes. Компоненты могут взаимодействовать с другими компонентами и узлами.

Running a ProjectЗапуск проекта#

To run a project, click the Play button on the toolbar. This will run an instance of the application in a separate window. Чтобы запустить проект, нажмите кнопку Play на панели инструментов. Это запустит экземпляр приложения в отдельном окне.

Примечание
You will see a green notification on successful compilation, while the red one signalizes that errors were found. Clicking the red message displays the details in the Console. All C# compilation and run-time errors are displayed in the Console.
For error messages to be displayed correctly on Windows, the language for non-Unicode programs should be the same as the current system locale.
Вы увидите зеленое уведомление об успешной компиляции, а красное сигнализирует об обнаружении ошибок. При нажатии на красное сообщение в консоли отображаются сведения. Все ошибки компиляции и выполнения C # отображаются в консоли.
Для правильного отображения сообщений об ошибках в Windows язык для программ, не поддерживающих Юникод, должен быть таким же, как текущий языковой стандарт системы.

Presets of custom run options are available in the list. By default, there is a single Default (Debug) preset with the default run options. Click the gear icon to configure the current selected preset of custom run options. В списке доступны предустановки пользовательских параметров запуска. По умолчанию есть одна предустановка Default (Debug) с параметрами запуска по умолчанию. Щелкните значок шестеренки, чтобы настроить текущий выбранный набор пользовательских параметров запуска.

In the window that opens the following run options are available: В открывшемся окне доступны следующие варианты запуска:

Configuration UNIGINE Engine build to be used UNIGINE Engine build to be used
Video API Graphics API to be used for rendering:
  • DirectX
  • OpenGL
Графический API, используемый для рендеринга:
  • DirectX
  • OpenGL
Resolution Screen size Размер экрана
Fullscreen

Run the instance in one of the following modes:Запустить экземпляр в одном из следующих режимов:

  • Disable — application shall run in the windowed modeDisable — отключен, приложение запускается в оконном режиме
  • Enable — application shall run in the fullscreen modeEnable — включен, приложение запускается в полноэкранном режиме
  • Borderless Window — application shall run in the fullwindow mode, when an application window is rendered without decorationsBorderless Window — приложение запускается в режиме без границ — полнооконном режиме, когда окно приложения отображается без дополнительных элементов
VR Mode Enable compatibility with one of supported VR headsets:
  • Disable
  • Vive
  • Oculus
Включить совместимость с одной из поддерживаемых гарнитур VR:
  • Disable
  • Vive
  • Oculus
Video Debug Enables the debug context of OpenGL or DirectX:
  • Disable
  • Messages
  • Asserts
Включает контекст отладки OpenGL или DirectX:
  • Disable
  • Messages
  • Asserts
Materials Loading Mode Selects the materials loading mode to be used:
  • Fastest Start - minimum memory consumption and maximum Engine loading speed. Recommended for fast iterations during the application development phase.Fastest Start - minimum memory consumption and maximum Engine loading speed. Recommended for fast iterations during the application development phase.
  • Full Materials - slightly slower loading at Engine's startup and more memory used than for the first mode, but less spikes. Can be used for a small project having a small number of materials (in case of satisfactory performance and sufficient memory amount).Full Materials - slightly slower loading at Engine's startup and more memory used than for the first mode, but less spikes. Can be used for a small project having a small number of materials (in case of satisfactory performance and sufficient memory amount).
  • Full Materials + Compile Shaders + Load Shaders - this mode ensures stable work and significant spikes reduction, but takes a lot of memory and increases loading time at startup. Recommended for production phase (when you hand over your application to the end user).Full Materials + Compile Shaders + Load Shaders - this mode ensures stable work and significant spikes reduction, but takes a lot of memory and increases loading time at startup. Recommended for production phase (when you hand over your application to the end user).
Fastest Start - minimum memory consumption and maximum Engine loading speed. Recommended for fast iterations during the application development phase.Full Materials - slightly slower loading at Engine's startup and more memory used than for the first mode, but less spikes. Can be used for a small project having a small number of materials (in case of satisfactory performance and sufficient memory amount).Full Materials + Compile Shaders + Load Shaders - this mode ensures stable work and significant spikes reduction, but takes a lot of memory and increases loading time at startup. Recommended for production phase (when you hand over your application to the end user).
Выбирает используемый режим загрузки материалов:
  • Fastest Start - minimum memory consumption and maximum Engine loading speed. Recommended for fast iterations during the application development phase. Fastest Start - минимальное потребление памяти и максимальная скорость загрузки двигателя. Рекомендуется для быстрых итераций на этапе разработки приложения.
  • Full Materials - slightly slower loading at Engine's startup and more memory used than for the first mode, but less spikes. Can be used for a small project having a small number of materials (in case of satisfactory performance and sufficient memory amount). Full Materials - немного медленнее загружается при запуске движка и используется больше памяти, чем в первом режиме, но меньше скачков. Может использоваться для небольшого проекта с небольшим количеством материалов (в случае удовлетворительной производительности и достаточного объема памяти).
  • Full Materials + Compile Shaders + Load Shaders - this mode ensures stable work and significant spikes reduction, but takes a lot of memory and increases loading time at startup. Recommended for production phase (when you hand over your application to the end user). Full Materials + Compile Shaders + Load Shaders - этот режим обеспечивает стабильную работу и значительное уменьшение скачков, но требует много памяти и увеличивает время загрузки при запуске. Рекомендуется для фазы производства (когда вы передаете свое приложение конечному пользователю).
Run Current World Run the current world opened in the Editor regardless of the default world set by logic. Запускать текущий мир, открытый в редакторе, независимо от мира по умолчанию, установленного логикой.
Arguments A set of startup command-line options. Набор параметров командной строки запуска .

On changing any custom run option and closing the window, the following actions will be performed depending on the preset selected: При изменении любого пользовательского параметра запуска и закрытии окна в зависимости от выбранной предустановки будут выполнены следующие действия:

  • If the Default (Debug) preset is selected in the list, a new *.launch asset file containing the custom run options will be created in the current folder of the Asset Browser. The corresponding preset will be available in the list of presets. Если в списке выбрана предустановка Default (Debug), в текущей папке обозревателя ресурсов будет создан новый файл ресурсов *.launch , содержащий настраиваемые параметры запуска. Соответствующий пресет будет доступен в списке пресетов.
  • If another preset is selected, changes will be applied to it. Если выбран другой пресет, к нему будут применены изменения.
Примечание
You can rename and delete presets of custom run options by renaming and deleting the corresponding *.launch assets. Вы можете переименовывать и удалять предустановки пользовательских параметров запуска, переименовывая и удаляя соответствующие ресурсы *.launch.

Debugging Your C# ComponentsОтладка ваших C# компонентов #

UnigineEditor automatically re-compiles your C# components as you make code modifications, save them and get back to the Editor. You will see a green notification on successful compilation, while the red one signalizes that errors were found. Clicking the red message displays the details in the Console. UnigineEditor автоматически повторно компилирует ваши компоненты C # по мере внесения вами изменений в код, сохраняет их и возвращаетесь в редактор. Вы увидите зеленое уведомление об успешной компиляции, а красное сигнализирует об обнаружении ошибок. При нажатии на красное сообщение в консоли отображаются подробные сведения.

You can inspect the source code of your C# components while your application is running regardless of whether the application is launched via the Play button right in the UnigineEditor, or built and launched from an IDE. Вы можете проверить исходный код ваших компонентов C # во время работы вашего приложения, независимо от того, запущено ли приложение с помощью кнопки Play прямо в UnigineEditor или создано и запущено из IDE.

See the Debugging C# Components article for details. Подробности см. в статье Отладка компонентов C # .

Building the ApplicationСборка приложения#

To create a debug or release build of your C# application, use the File -> Create Build option available in UnigineEditor. Чтобы создать отладочную или выпускную сборку вашего приложения C #, используйте параметр File -> Create Build, доступный в UnigineEditor.

See the Packing a Final Build for Publishing article for details. Подробности см. в статье Финальная сборка проекта для публикации .

UsageИспользование#

As an example, you can use components to implement logic of enemies chasing the player in your game: regardless of their size, shape, speed, all of them will check player's position, and try to find a path to move closer to it as fast as they can. The code will be basically the same, it'll just use different parameters (speed, mesh, or sounds maybe), so you can put all these parameters to a component (to be able to change them at any time) and the code to the corresponding component class (e.g. place enemies in the world in the Init() and chase the player in the Update() method). В качестве примера, вы можете использовать компоненты для реализации логики преследования врагов в вашей игре: независимо от их размера, формы, скорости, все они будут проверять позицию игрока, и постарайтесь найти путь, чтобы приблизиться к нему как можно быстрее. Код будет в основном таким же, он просто будет использовать разные параметры (скорость, сетку или звуки, возможно), поэтому вы можете поместить все эти параметры в компонент (чтобы иметь возможность изменять их в любое время) и код для соответствующий класс компонента (например, разместить врагов в мире в Init() и преследовать игрока методом Update()).

Then you should simply assign the component to all enemy objects and set up parameters (define meshes, sounds, etc.). The Component System will do the rest: execute your code at the corresponding stages of the Engine's main loop for all enemy objects using their specific parameters. Should you decide to modify your code later, you can do that in a single source — component class. Затем вы должны просто назначить компонент всем объектам противника и настроить параметры (определить сетки, звуки и т. д.). Система компонентов сделает все остальное: выполнит ваш код на соответствующих этапах основного цикла Engine для всех вражеских объектов, используя их определенные параметры. Если вы решите изменить свой код позже, вы можете сделать это в едином исходном классе компонентов.

Integration with the Microprofile tool, enables you to monitor overall performance of the Component System, as well as to add profiling information for your custom components. Интеграция с инструментом Microprofile позволяет контролировать общую производительность системы компонентов, а также добавлять информацию профилирования для ваших пользовательских компонентов.

Последнее обновление: 07.04.2022
Build: ()