что такое инспектор в юнити
Что такое инспектор в юнити
Любое отображённое в инспекторе свойство можно изменять напрямую. Даже переменные скрипта могут изменяться без изменения самого скрипта. Вы можете использовать изменение переменных в инспекторе для экспериментов в прямом времени и тем самым придумать какие-нибудь элементы для вашей игры. В скрипте, если вы задали public переменную объектного типа (вроде GameObject или Transform), вы можете перетянуть GameObject или префаб в инспектор, чтобы его назначить.
Нажмите на вопросительный знак рядом с именем любого компонента в инспекторе, чтобы открыть страницу справки по этому компоненту.
Добавление компонентов из меню Component
Вы можете нажать на иконку маленькой шестерни (или правой кнопкой по имени компонента), чтобы открыть контекстное меню для определённого компонента.
Также инспектор покажет любые настройки импорта для выбранного ассета.
Нажмите Apply, чтобы реимпортировать ваш ассет.
Префабы
Если у вас выбран префаб, то в инспекторе будет доступно несколько дополнительных кнопок. Чтобы получить больше информации о префабах, см. Prefab.
Иконки
Для всех элементов Unity инспектор отображается с отличительной иконкой в верхнем левом углом рядом с именем. Для игрового объекта или префаба, можно установить пользовательскую иконку, чтобы определить объект в сцене. Если вы нажмёте на иконку, то появится меню выбора:-
Большие, продолговатые иконки сверху меню будут отображать имя объекта в окне Scene View на панели соответствующего цвета.
Иконки поменьше, в нижней части меню не будут отображать имени объекта, а просто будут идентифицировать его при помощи небольшого значка выбранной формы и цвета. Кнопка Other снизу меню позволит выбрать любую текстуру из проекта для идентификации объекта.
Метки
Снизу справа у панели есть кнопка c нарисованным многоточием на ней. После нажатия на эту кнопку, появится меню доступных меток.
Вы можете выбрать один или более элемент из меню меток, чтобы пометить ассет ими (они также появятся на панели Labels). Если вы нажмёте ещё раз на одну из активных меток, то она будет удалено из ассета.
В меню также есть текстовая форма, позволяющая вам указать фильтр поиска по метакм в меню. Если вы введёте имя метки, которой ещё не существует, и нажмёте Return/Enter, то новая метка будет добавлена в список и применена к выбранному ассету. Если вы удалите пользовательские метки из всех ассетов в проекте, то они исчезнут и из списка.
Как только вы примените метки к вашим ассетам, вы сможете использовать их, чтобы улучшить процесс поиска в Project Browser.
Variables and the Inspector
When creating a script, you are essentially creating your own new type of component that can be attached to Game Objects just like any other component.
Just like other Components often have properties that are editable in the inspector, you can allow values in your script to be edited from the Inspector too.
This code creates an editable field in the Inspector labelled “My Name”.
Unity создает метку в окне Inspector путем добавления пробела везде, где в имени переменной встречается заглавная буква. Однако это исключительно в целях отображения, и вы должны всегда в коде использовать имя переменной. Если вы отредактируете значение переменной и затем нажмете Play, вы увидите, что сообщение включает введенный вами текст.
In C#, you must declare a variable as public to see it in the Inspector. In UnityScript, variables are public by default unless you specify that they should be private:
Unity позволяет изменять значение переменных скрипта в запущенной игре. Это очень полезно чтобы увидеть эффекты от изменений сразу же, без остановки и перезапуска. Когда проигрывание оканчивается, значения переменных сбрасываются в то состояние, которое они имели до нажатия кнопки Play. Это гарантирует, что вы свободно можете играть с настройками объектов, не боясь что-то испортить.
The Inspector window
The Inspector window docked in the Unity Editor
Opening an Inspector window
To open an Inspector window, do one of the following:
You can open as many Inspector windows as you want, and reposition, dock, and resize them in the same way you can any other window.
Controlling Inspector window focus
By default, an Inspector window displays properties for the current selection. The contents of the Inspector change whenever the selection changes. To keep the same set of properties open, regardless of the current selection, do one of the following:
Inspecting items
What you can see and edit in an Inspector window depends on what you select. This section describes what an Inspector window displays for different types of items you can select.
Inspecting GameObjects
When you select a GameObject (for example, in the Hierarchy or Scene view An interactive view into the world you are creating. You use the Scene View to select and position scenery, characters, cameras, lights, and all other types of Game Object. More info
See in Glossary ), the Inspector displays the properties of all of its components and Materials. You can edit the properties, and reorder the components in the Inspector window.
Inspecting custom script components
When GameObjects have custom script components attached, the Inspector displays the 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 ’ public variables. You can edit script variables in the same way as you edit any other properties, which means that you can set parameters and default values in your scripts without modifying the code.
Inspecting Assets
When you select an Asset Any media or data that can be used in your game or project. An asset may come from a file created outside of Unity, such as a 3D Model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary (for example, from the Project window A window that shows the contents of your Assets folder (Project tab) More info
See in Glossary ), the Inspector displays settings that control how Unity imports and uses the Asset at runtime.
Each type of Asset has its own settings. Examples of Asset import settings that you edit in an Inspector window include the:
Inspecting settings and preferences
When you open the Project Settings A broad collection of settings which allow you to configure how Physics, Audio, Networking, Graphics, Input and many other areas of your project behave. More info
See in Glossary (menu: Editor > Project Settings), Unity displays them in an Inspector window.
Inspecting Prefabs
When you work with Prefabs, the Inspector window displays some additional information and provides some additional options. For example:
For more information about working with Prefabs in the Inspector window, see the Prefabs An asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary section.
Inspecting multiple Items
When you have two or more items selected, you can edit all of the properties they have in common in an Inspector window. Unity copies the values you supply to all the selected items. The Inspector window displays a count of the number of selected items.
Multiple GameObjects
When you select multiple GameObjects, the Inspector window displays all of the components they have in common.
Multiple Assets
When you select multiple Assets of the same type, the Inspector window displays all of the properties they have in common.
When you select multiple Assets of different types, the Inspector displays a list that shows how many of each type of Asset are selected. Click any item in the list to Inspect all Assets of that type.
Inspector showing multiple selected Assets of different types
Multiple Prefabs
You can inspect multiple selected instances of a Prefab in the same way as you edit multiple GameObjects, but the Inspector hides the Select, Revert, and Apply buttons (see Editing a Prefab via its instances).
Locating an Inspector window’s source
When you open a GameObject or Asset in an Inspector window, you can locate it in the Scene A Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary view or Project View using the Ping command.
From the Inspector window’s More Items (⋮) menu, select Ping. Unity highlights the item in the Hierarchy view or the Project view.
Using the Inspector (Использование панели Inspector)
Inspecting Game Objects
Панель Inspector используется для того, чтобы просматривать и редактировать Свойства объектов различными способами.
When you select a GameObject in the Hierarchy or Scene View, the Inspector will show the Properties of all Components and Materials on that object and allow you to edit them. The image above shows the inspector with the default 3D camera GameObject selected. In addition to the object’s position, rotation and scale values, all the properties of the camera are available to edit.
Inspecting Script Variables
When Game Objects have custom Script components attached, the public variables of that script are also shown in the inspector and can be viewed and edited like the properties of Unity’s built-in components. This allows you to set parameters and default values in your scripts easily without modifying the code.
Inspecting Assets
When an Asset is selected in your Project Window, the Inspector will show you the settings related to how that asset is imported and used at runtime. Each type of asset will have a different arrangement of settings. Below are some examples of the inspector showing the import settings for other asset types:
Inspector отображает геймобъекта c компонентами
Inspector отображает геймобъекта c компонентами
Inspector отображает геймобъекта c компонентами
Project Settings
Настройки инспектора
The Inspector Lock and the Inspector Debug Mode are two useful options that can help you in your workflow.
Блокировка
Normally, the inspector shows the details of the currently selected object but it is sometimes useful to keep one object in the inspector while you work with others. To enable this, the inspector has a Lock mode that you can activate with the small padlock icon to the top right of the inspector window.
Note that you can have more than one inspector open at once (menu: Add Tab from the inspector tab menu), so you could keep one locked and have a second one to show the current selection. Below is an example of adding a new tab and locking it so it retains the desired view. The result is two Inspector windows, both visible, each showing different content.
Adding a new tab, docking it under the current inspector tab, and locking it.
Режимы Нормальный/Отладка
Другая опция в меню, это выбор между режимом Normal(нормальный) и Debug(отладка) Обычно, инспектор отображает пользовательский редактор для ассета или компонента, если есть доступный, но иногда удобнее напрямую видеть параметры. Режим отладки отображает только параметры, в отличие от пользовательского редактора, а для скриптов он также отображает и private переменные (хотя их значения не могут быть изменены так, как public переменные).
Скрипт отображаемый в режиме отладки с затемнёнными private переменными
Как и режим блокировки, режим Нормальный/Отладка применяется индивидуально для каждого инспектора, таким образом у вас может быть открыто 2 инспектора одновременно так, чтобы видеть оба окна.