Unity default references will only be applied in edit mode что это
Serialize Reference в Unity
Всем добрый день. Эта статья про относительно новую фичу Serialize Reference. Появилась она в 2019 версии.
Оглавление:
Что это такое и зачем оно нужно
Как работать с этим
В данных примерах под типом object скрывается сериализация ExampleFirst и ExampleSecond.
Плюсы
Это отвязка от монобеха
Отказ от изменения реализации поведения через интерфейс и множество реализаций через компоненты
Это хранение данных в одном листе, вместо постоянного раздувания количества листов ради новых данных
Никаких кастомных решений для редактора. Отображение экземпляров происходит за счёт стандартных решений юнити.
Минусы
При изменении имени и неймспейса, ломается сериализация. Для того чтобы починить сериализацию после изменения имении и неймспейса, требуется использовать movefromattribute в котором будет указано, как раньше назывался данный тип, и где находился
Юнитехи не предоставили удобного инструментария для работы в редакторе из под капота (Будет описано ниже)
Как с этим работать
Мы теперь знаем что наше любимое юнити умеет сериализовывать абстрактные поля, но как заставить всё это удобно работать?
Суть в том, что редактор сериализует экземпляр, а не поле. И если в него ничего не было вложено, то собственно ему и нечего сериализовывать и отображать вам. В случае обычного SerializeField, редактор автоматически инициализирует ваше поле, даже если вы не укажете это в коде
Но как вложить экземпляр в данное поле? Дефолтными способами из коробки только через дефолтную инициализацию. Юнитеки не предоставили удобного инструментария для работы с данными полями. Единственное что вам дали, это 3 поля у данных типа SerializeProperty:
Для отрисовки данных экзмепляров юнити использует стандартную механиху PropertyDrawer. Т.е. если вам нужно будет заоверрайдить отрисовку, либо сделать декорацию с помощью PropertyAttribute, то это всё также работает в SerializeReference.
Для инициализации данных полей можно писать кастомный инстурментарий используя поля SerializeProperty описанные выше, либо использовать данный [ассет](https://github.com/elmortem/serializereferenceeditor)
Самое важное ещё понимать с чем это сериализация может работать, а с чем нет. Данная шпаргалка есть в доке [юнитехов](https://docs.unity3d.com/ScriptReference/SerializeReference.html)
Тип поля не должен наследоваться от UnityEngine.Object
Тип поля может быть абстрактным классом/интерфейсом
Применение аттрибута SerializeReference к листу/массиву приводит его применение ко всем его элементам. Т.е. List работает.
Референсы данных полей не могут быть у разных UnityEngine.Object. Т.е. если вы присваивали в редакторе один и тот же экземпляр, то после десериализации это будут разные экземпляры но с одним и тем же наполнением.
Тип данных который пытаетесь сериализовать, должен быть почемен атрибутом [Serializable]
Примеры
Я также для себя пытался реализовывать подобную фичу, но без некоторых элементов. Ничего сложного в этом нет. Код как это легко реализовать есть ниже:
Preferences
Unity provides a number of preferences that let you customize the behavior of the Unity Editor.
To access the Preferences window, go to Edit > Preferences (Windows) or Unity > Preferences (macOS) from the main menu in Unity. The following preference categories are available:
Navigating the Preferences window
Use the search box to filter the list of settings categories, and highlight keywords in the details pane on the right.
General
General preferences let you customize the overall behavior for working in Unity.
Code coverage helps measure how much of your code has been executed. It is normally associated with automated tests, but you can gather coverage data in Unity at any time when the Editor is running.
You can use the Code Coverage package to gather and present code coverage information.
See in Glossary at World coordinates 0,0,0. Otherwise, Unity uses the Scene pivot (in front of the Scene view Camera).
This allows you to throttle Editor performance, and reduce consumption of CPU resources and power.
For example, if you want to test the Editor’s performance, set this property to No Throttling. If you want to conserve power (for example, to prolong battery life on a laptop computer), set this property to one of the throttled modes.
In throttled modes, the Editor stops idling if you interact with it (for example, by panning in the Scene view).
Note: In Play mode, Unity ignores any throttling that you apply using this preference. The editor updates as fast as possible unless you enable the VSync option in the Game view, or set Application.targetFrameRate to a value other than –1.
This mode consumes a lot of CPU resources. If you are using a laptop computer, it can cause the battery to drain quickly.
When you select this option the Frame Throttling (milliseconds) property appears.
Use the Max Sprite A 2D graphic objects. If you are used to working in 3D, Sprites are essentially just standard textures but there are special techniques for combining and managing sprite textures for efficiency and convenience during development. More info
See in Glossary Atlas Cache Size (GB) preference to set the maximum size of the Sprite Atlas A texture that is composed of several smaller textures. Also referred to as a texture atlas, image sprite, sprite sheet or packed texture. More info
See in Glossary cache folder. Whenever possible, Unity keeps the size of this folder below this level.
2D scope on the Preferences window
Analysis
Analysis scope on the Preferences window
Property | Function |
---|---|
Frame count | Set the maximum number of frames for the Profiler to capture. You can set this number between 300 and 2,000. |
Show stats for ‘current frame’ | By default, when you select the Current Frame button and enter Current Frame mode, the frame indicator line does not have annotations with the stats for the current frame. This is because the stats annotations might make it difficult to view data in real-time. To display the annotations, enable this setting. |
Default recording state | Select which recording state the Profiler should open in. Choose from Enabled, Disabled, or Remember. Enabled keeps the Record button enabled between sessions, while Disbled disables it, regardless of whether you turn it on or off during your profiling session. The Remember state remembers whether you have enabled or disabled the Record button during your session and keeps it at its last state next time you open the Profiler window. |
Default editor target mode | Select what mode the Attach to Player dropdown should target by default. Choose from either Playmode or Editor. |
Cache Server
Any time an Asset changes, Unity automatically re-imports it. Setting up a Cache Server drastically reduces the time it takes to import Assets. You can set up a Cache Server using remote hosting or stored on your local computer.
Cache Server scope on the Preferences window
Property | Function |
---|---|
New Projects default asset pipeline | Select the default asset pipeline for new Projects. |
Active version | Displays the current asset pipeline version. |
Asset pipeline v1 (deprecated) | |
Cache Server Mode | Define the Cache Server A standalone app that you can run on your local computer that stores the imported asset data to reduce the time it takes to import assets. More info See in Glossary mode. Local: Use a local Cache Server on this computer. The preferences for Local storage appear. Remote: Use a Cache Server hosted on a remote computer. The preferences for Remote hosting appear. By default the Cache Server is disabled. |
Asset pipeline v2 | |
Cache Server Default Mode | Define whether the Cache Server is enabled or disabled by default. You can override this per Project in the Unity Editor settings. For more information on using Asset pipeline v2, see Unity Accelerator. |
Default IP address | Set the default IP address for the Cache Server to use. You can override this per Project in the Unity Editor settings. |
Check Connection | Click this button to attempt to connect to the remote Cache Server. |
Remote hosting
These preferences are only available when Use Cache Server is set to Remote.
Remote Cache Server preferences
Property | Function |
---|---|
IP Address | Enter the IP address of the dedicated cache server that an administrator set up. |
Check Connection | Click this button to attempt to connect to the remote Cache Server. |
Local storage
These preferences are only available when the Use Cache Server is set to Local.
Local Cache Server preferences
Property | Function |
---|---|
Maximum Cache Size (GB) | Specify the maximum size in gigabytes for the Cache Server on this computer’s storage. The minimum size is 1GB. The maximum size is 200GB. The default cache size is 10GB. |
Custom cache location | Enable this option to specify a location where you want to store the cache. |
Cache Folder Location | Click the Browse button to specify a location for the cache. |
Cache size is … | Message displaying the current size of the cache. Before clicking the Check Cache Size button, this appears as Cache size is unknown. After clicking the button, the calculated cache size appears in the message. |
Check Cache Size | Click this to find out how much storage the Local Cache Server is using. This operation can take some time to complete if you have a large project. |
Clean Cache | Delete the contents of the cache. |
Cache Folder Location | Displays the current cache folder location. |
Colors
The Colors preferences let you choose the colors that Unity uses when displaying various user interface elements.
Colors scope on the Preferences window
External Tools
Use the External Tools preferences to set up external applications for scripting, working with images, and source control.
Note: When you change this setting, you need to restart Unity for the change to take effect.
For more information, see the Revision Control Diff/Merge section below.
Revision Control Diff/Merge
Unity currently supports these tools:
Note: These are third-party tools that Unity doesn’t include by default. You must download and install them separately.
To set up a custom revision tool, follow these steps:
To specify file layout in the revision tool, use these arguments:
Property | Function |
---|---|
#LTITLE | Left title |
#RTITLE | Right title |
#ATITLE | Ancestor title |
#LEFT | Left file |
#RIGHT | Right file |
#ANCESTOR | Ancestor file |
#OUTPUT | Output file |
#ABSLEFT | Absolute path to the left file |
#ABSRIGHT | Absolute path to the right file |
#ABSANCESTOR | Absolute path to the ancestor file |
#ABSOUTPUT | Absolute path to the output file |
SourceGear DiffMerge P4Merge
GI Cache
The Global Illumination A group of techniques that model both direct and indirect lighting to provide realistic lighting results. Unity has two global illumination systems that combine direct and indirect lighting.: Baked Global Illumination, and Realtime Global Illumination.
See in Glossary (GI) system uses a cache on each computer to store intermediate files used to pre-compute real-time Global Illumination. All projects on the computer share the cache.
GI Cache scope on the Preferences window
Property | Function |
---|---|
Maximum Cache Size (GB) | Use the slider to set the maximum GI cache folder size. Unity keeps the GI cache folder size below this number whenever possible. Unity periodically deletes unused files to create more space (deleting the oldest files first). This is an automatic process, and doesn’t require you to do anything. Note: If the current Scene is using all the files in the GI cache, increase your cache size. Otherwise, resource-intensive recomputation occurs when baking. This can happen when the Scene is very large or the cache size is too small. |
Custom cache location | Enable this option to allow a custom location for the GI cache folder. By default, the GI cache is stored in the Caches folder. All Projects share the cache folder. Tip: Storing the GI Cache on an SSD drive can speed up baking in cases where the baking process is I/O bound. |
Cache Folder Location | Click the Browse button to specify a location for the cache. |
Cache compression | Enable this option to allow Unity to compress files in the GI cache and reduce the size of the generated data. The files are LZ4-compressed by default, and the naming scheme is a hash and a file extension. The hashes are computed based on the inputs to the lighting system, so changing any of the following can lead to recomputation of lighting: — Materials (Textures, Albedo, Emission) — Lights — Geometry — Static flags — Light Probe groups — Reflection probes — Lightmap Parameters Tip: If you need to access the raw Enlighten data, disable Cache Compression and clean the cache. |
Clean Cache | Use this button to clear the cache directory. It is not safe to delete the GI Cache directory manually while the Editor is running. This is because the Editor creates the GiCache folder when it starts and maintains a set of references to those files. The Clean Cache button ensures that the Editor releases all references to the files on disk before they are deleted. |
Cache size is | Displays the current size of the cache. |
Cache Folder Location | Displays the current cache folder location. |
Scene View
Use the Scene View preferences to customize object placement and visibility while editing.
Scene View scope on the Preferences window
Property | Function |
---|---|
Create Objects at Origin | Enable to create new objects at origin (as opposed to the Scene pivot). Disabled by default. |
Line Thickness | Set the line thickness of your transform tools. |
Enable filtering while searching | Enable to gray out any non-matching items in the Scene view. Enabled by default. |
Enable filtering while editing LOD groups | Enable to gray out other objects in the scene while editing LOD groups. Enabled by default. |
UI Scaling
The UI (User Interface) Allows a user to interact with your application. More info
See in Glossary Scaling preferences let you define how to scale UI text and icons in the Unity Editor.
UI Scaling scope on the Preferences window
Property | Function |
---|---|
Use default desktop setting | Enable this setting to use your computer’s default settings for scaling UI text and icons. |
Current scaling | Displays the current scaling value. |
Use custom scaling value | Override the scaling value. |
Custom package preferences
Some Asset Store or Unity packages add their own custom preferences to the Preferences window. Generally these use the package name as the preferences category. In this example, you can see the Cinemachine package preferences:
Package-specific preferences appear in the scope list
For information about a specific package’s preferences, see the documentation for that package. This section contains documentation for standard Unity preferences only.
2020–05–04 Page amended
Interaction Mode Preferences added in 2019.3
Added Analysis and UI Scaling tabs, and removed Grid Brush and Tile Palette tabs in 2019.3
Added Gradle for Android options to the External Tools section in 2019.1.
Removed keys and added further options to the Tile Palette Preferences in 2019.1. NewIn20191
Selection outline color preference for child GameObjects added in 2018.3
New unified settings and other updates for Unity 2018.3
Script Changes While Playing and Device To Use drop-down menus added in Unity 2018.2
Updated list of external script editors in 2018.1