Unity minify что такое
Unity — Enable Multidex или слишком много методов
С чего все началось
Всем привет. На определенном этапе разработки игры под Android на движке Unity я столкнулся с одной проблемой при билде. После добавления в проект таких плагинов как Appodeal и Google Play Games количество используемых методов превысило 65K и во время билда появилась следующая ошибка:
Почитав документацию Appodeal, понял что надо включить Multidex. Решил это сделать. На сайте была ссылка с инструкцией для Android Studio. А мы то с вами на Unity, что же делать?
А все довольно просто надо сделать всего три действия:
Включить систему сборки Gradle
Чтобы в своем проекте на Android включить систему Gradle в Unity выполним пару действий
Изменение настроек Gradle
1. Чтобы изменить настройки Gradle, вам сначала нужно получить файл настроек Gradle, который расположен в папке (Assets/Plugins/Android/mainTemplate.gradle). Если файла mainTemplate.gradle скачайте по ссылке и вставьте по адресу Assets/Plugins/Android/:
2. Если файл у вас уже есть, добавляем строку multiDexEnabled true в объект defaultConfig
3. Если минимальный уровень API Android равен 20 или ниже, добавьте эту строку compile ‘com.android.support:multidex:1.0.1’
4. Закомментируем или удалим строки:
Окончательный вид файла:
Инициализация Multidex
Если минимальный уровень API Android, установленный на 20 или ниже.
Обновите файл манифеста, расположенный в Assets/Plugins/Android/AndroidManifest.XML. Если у вас нет этого файла, вам придется его создать. Вы можете найти AndroidManifest по умолчанию.xml в месте установки Unity. Но вам также придется вручную применить параметры проекта вашего приложения: имя пакета, разрешения, параметры конфигурации и другую информацию.
Если вы только что создали новый файл манифеста или у вас уже был он, вы просто добавляете этот параметр(android:name) следующим образом:
На этом все. Ошибка исчезнет, и вы спокойно сбилдите свой проект.
Gradle for Android
Gradle is an Android build system that automates a number of build processes and prevents many common build errors. In Unity, Gradle reduces the method reference count in DEX (Dalvik Executable format) files, which means you are less likely to come across DEX limit problems.
Unity version | Gradle version |
---|---|
2020.3 starting from 2020.3.15f1 | 6.1.1 |
2020.1, 2020.2, 2020.3 up to and including 2020.3.14f1 | 5.6.4 |
2019.4 | 5.1.1 |
To learn more about:
Building or exporting a Gradle project
To build a Gradle project, follow these steps:
Exported Gradle project structure
Unity 2019.3 and newer versions create a Gradle project with two modules:
build.gradle templates
Gradle templates describe and configure how to build your Android app with Gradle. Each Gradle template represents a singleGradle project. Gradle projects can include, and depend on other Gradle projects.
A Gradle template consists of the following files:
Customizing your Gradle build
You can provide a custom Gradle build template and select minification options in the Publishing Settings section of the Player Settings Settings that let you set various player-specific options for the final game built by Unity. More info
See in Glossary window.
Providing a custom Gradle build template
You can use a custom build.gradle file for the unityLibrary module when you build the APK from Unity. This file contains specific build instructions specified in template variables. For a list of template variables, see the next section.
To use your own build.gradle file for the unityLibrary module, follow these steps:
Unity then generates a default mainTemplate.gradle file in your Project’s Assets/Plugins/Android/ folder. The path to the new file also appears under the Custom Main Gradle Template option in the Player Settings. Double-click the mainTemplate.gradle file in the Project view to open it in an external text editor.
mainTemplate.gradle file in the Project view for the unityLibrary module
By default, Unity uses the settingsTemplate.gradle file from the Unity install directory to create the settings.gradle file for your build. The settings.gradle file contains project components which are involved in the build process. Unity creates the following components by default, which should always be included in the settings.gradle file:
Additionally, if you add Android library plugins to your project, Unity automatically includes them in the settings file by replacing the **INCLUDES** entry.
If you want to add additional components to the settings.gradle file that Unity doesn’t include by default, create a settingsTemplate.gradle file in your project’s Assets/Plugins/Android/ folder. This overrides the default template.
If you use your own settingsTemplate.gradle file, it must contain the following lines:
IPostGenerateGradleAndroidProject
IPostGenerateGradleAndroidProject returns the path to the unityLibrary module. This keeps everything similar to versions earlier than Unity 2019.3 and doesn’t require any further changes, which means Unity can reach the app’s manifest and resources in a consistent way across versions.
Template variables
The mainTemplate.gradle file can contain the following variables:
Variable: | Description: |
---|---|
DEPS | List of project dependencies See in Glossary ; that is, the libraries that the Project uses. |
APIVERSION | API version to build for (for example, 25). |
MINSDKVERSION | Minimum API version (for example, 25). |
BUILDTOOLS | SDK Build tools used (for example, 25.0.1). |
TARGETSDKVERSION | API version to target (for example, 25). |
APPLICATIONID | Android Application ID (for example, com.mycompany.myapp). |
MINIFY_DEBUG | Enable minify for debug builds (true or false). |
PROGUARD_DEBUG | Use proguard for minification in debug builds (true or false.) |
MINIFY_RELEASE | Enable minify for release builds (true or false). |
PROGUARD_RELEASE | Use proguard for minification in release builds (true or false). |
USER_PROGUARD | Custom user proguard file (for example, proguard-user.txt ). |
SIGN | Complete the signingConfigs section if this build is signed. |
SIGNCONFIG | Set to signingConfig signingConfig.release if this build is signed. |
DIR_GRADLEPROJECT | The directory where Unity creates the Gradle project. |
DIR_UNITYPROJECT | The directory of your Unity Project. |
Minification
You can use Proguard minification to shrink and optimize your app. To activate this option, follow these steps:
Note: Proguard might strip out important code that your app needs, so use these options carefully.
To generate a custom proguard.txt file, enable the User Proguard File setting in the Publishing Settings section of the Player Settings. This immediately generates the proguard.txt file in your Project’s Assets/Plugins/Android/ folder.
To learn more about ProGuard, see the ProGuard manual.
Errors when building with Gradle
If an error occurs when you use Gradle to build your app for Android, Unity displays an error dialog box. Select the Troubleshoot button to open the Gradle troubleshooting Unity documentation in your system’s browser.
Пишем плагин для Unity правильно. Часть 2: Android
В предыдущей части мы рассмотрели основные проблемы написания нативных плагинов на Unity под iOS и Android, а также методы их решения для iOS. В этой статье я опишу основные рецепты по решению этих проблем для Android, стараясь сохранить схожую структуру взаимодействия и порядок их рассмотрения.
Библиотеки для Android в Unity могут быть представлены в виде Jar (только скомпилированный java код), Aar (скомпилированный java код вместе с ресурсами и манифестом), и исходников. В исходниках желательно хранить только специфичный для данного проекта код с минимальным функционалом, и то это необязательно и не очень удобно. Лучший вариант — завести отдельный gradle проект (можно прямо в репозитории с основным Unity проектом), в котором можно разместить не только код библиотеки, но и unit-тесты, и тестовый Android проект с Activity для быстрой сборки и проверки функционала библиотеки. А в gradle скрипт сборки этого проекта можно сразу добавить task, который будет копировать скомпилированный Aar в Assets:
Здесь my-plugin — название проекта библиотеки; deployAarPath — путь, по которому копируется компилируемый файл, может быть любым.
Использовать Jar сейчас также нежелательно, потому что Unity уже давно научилась поддерживать Aar, а он дает больше возможностей: кроме кода можно включать ресурсы и свой AndroidManifest.xml, который будет сливаться с основным при gradle-сборке. Сами файлы библиотек не обязательно складывать в Assets/Plugins/Android. Правило действует такое же, как и для iOS: если пишете стороннюю библиотеку, складывайте все в подпапку внутри вашей специфической папки с кодом и нативным кодом для iOS — проще будет потом обновлять или удалять пакеты. В других случаях можно хранить, где хочется, в настройках импорта Unity можно указать, включать ли файл в Android сборку или нет.
Попробуем организовать взаимодействие между Java и Unity кодом без использования GameObject аналогично примерам для iOS, реализовав свой UnitySendMessage и возможность передавать колбеки из C#. Для этого нам понадобятся AndroidJavaProxy — С# классы, используемые как реализации Java интерфейсов. Названия классов оставлю те же, что из предыдущей статьи. При желании их код можно объединить с кодом из первой части для мультиплатформенной реализации.
На стороне Java определим интерфейс для получения сообщений и класс, который будет регистрировать, а потом и делегировать вызовы вышеописанному JavaMessageHandler. Попутно решим задачу перенаправления потоков. Так как в отличие от iOS, на Android Unity создает свой поток, имеющий loop circle, можно создать android.os.Handler при инициализации и передавать выполнение ему.
Теперь добавим возможность вызывать Java функции с передачей колбека, используя все тот же AndroidJavaProxy.
На стороне Java объявляем интерфейс колбека, который потом будем использовать во всех экспортируемых функциях с колбеком:
В качестве аргумента колбека я использовал Json, также как и в первой части, потому что это избавляет от необходимости описывать интерфейсы и AndroidJavaProxy на каждый необходимый в проекте набор разнотипных аргументов. Возможно, вашему проекту больше подойдет string или array. Привожу пример использования с описанием тестового сериализуемого класса в качестве типа для колбека.
Типичная проблема при написании плагинов под Android для Unity: отлавливать жизненные циклы игрового Activity, а также onActivityResult и запуск Application. Обычно для этого предлагают отнаследоваться от UnityPlayerActivity и переопределить класс у launch activity в манифесте. То же можно сделать для Application. Но в этой статье мы пишем плагин. Таких плагинов в больших проектах может быть несколько, наследование не поможет. Нужно интегрироваться максимально прозрачно без необходимости модификаций основных классов игры. На помощь придут ActivityLifecycleCallbacks и ContentProvider.
Не забудьте зарегистрировать InitProvider в манифесте (Aar библиотеки, не основном):
Тут используется тот факт, что Application на старте создает все объявленные Content Provider. И если даже он не предоставляет никаких данных, какие должен возвращать нормальный Content Provider, в методе onCreate можно сделать что-то, что обычно делается на старте Application, например зарегистрировать наш ActivityLifecycleCallbacks. А он уже будет получать события onActivityCreated, onActivityStarted, onActivityResumed, onActivityPaused, onActivityStopped, onActivitySaveInstanceState и onActivityDestroyed. Правда события будут идти от всех активити, но определить основное из них и реагировать только на него ничего не стоит:
Не хватает только onActivityResult, которое обычно требуется для возврата результата от показа нативного экрана поверх игры. Напрямую этот вызов получить, к сожалению нельзя. Но можно создать новое Activity, которое покажет требуемое Activity, потом получит от него результат, вернет нам и финиширует. Главное исключить его из истории и сделать прозрачным, указав тему в манифесте, чтобы при открытии не мелькал белый экран:
Таким образом можно реализовать необходимый функционал, не прибегая к модификации основных классов Unity Java, и аккуратно упаковать манифест с кодом и ресурсами в Aar библиотеку. Но что делать с пакетами зависимостей из maven репозиториев, которые требуются нашему плагину? Unity генерирует gradle проект, в котором все java библиотеки проекта складываются в libs экспортируемого проекта и подключаются локально. Дубликатов быть не должно. Другие зависимости автоматом включены не будут. Положить зависимости рядом с скомпилированным Aar не всегда хорошая идея: чаще всего эти же зависимости нужны и другим Unity плагинам. И если они положили тоже свою версию в unitypackage, произойдет конфликт версий, gradle при сборке ругнется на дубликат классов. Также зависимости зависят от других пакетов, и вручную составить эту цепочку зависимостей, выкачав из maven-репозитория все, что нужно — задача не такая уж простая.
Искать в проекте дубликаты тоже утомительно. Хочется автоматизированного решения, которое само скачает нужные библиотеки нужных версий в проект, удаляя дубликаты. И такое решение есть. Данный пакет можно скачать самостоятельно, а также он поставляется вместе с Google Play Services и Firebase. Идея в том, что в Unity проекте создаем xml файлы со списком зависимостей, требуемых плагинам по синтаксису, схожему с определением в build.gradle (с указанием минимальных версий):
Далее после установки или изменения зависимостей в проекте выбираем в меню Unity редактора Assets → Play Services Resolver → Android Resolver → Resolve и вуаля! Утилита просканирует xml объявления, создаст граф зависимостей и все нужные пакеты зависимостей нужных версий скачает из maven репозиториев в Assets/Plugins/Android. Причем она отмечает в специальном файле скачанное и в следующий раз заменяет его новыми версиями, а те файлы, что положили мы, она трогать не будет. Также есть окно настроек, где можно включить автоматическое разрешение зависимостей, чтобы не нажимать Resolve через меню, и много других опций. Для работы требуется Android Sdk, установленный на компьютере вместе с Unity и выбранный target — Android. В том же файле можно писать CocoaPods зависимости для iOS билдов, и в настройках задать, чтобы Unity генерировала xcworkspace с включенными зависимостями для основного проекта XCode.
Unity относительно недавно стала полноценно поддерживать gradle сборщик для Android, а ADT объявила как legacy. Появилась возможность создавать template для gradle конфигурации экспортируемого проекта, полноценная поддержка Aar и переменных в манифестах, слияние манифестов. Но плагины сторонних sdk еще не успели адаптироваться под эти изменения и не используют те возможности, что предоставляет редактор. Поэтому мой совет, лучше модифицируйте импортируемую библиотеку под современные реалии: удалите зависимости и объявите их через xml для Unity Jar Resolver, скомпилируйте весь java код и ресурсы в Aar. Иначе каждая последующая интеграция будет ломать предыдущие и отнимать все больше времени.
Android Player settings
Player Settings for Android.
Documentation for the properties is grouped according to their respective sections in the Player UI (User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary :
Use the Icon section to specify icons to represent your application on the device.
Resolution and Presentation
Use the Resolution and Presentation section to customize aspects of the screen’s appearance.
Other Resolution and Presentation settings are grouped under the following sections:
Resolution Scaling
Use the Resolution Scaling section to customize settings relating to screen resolution scaling. Using a resolution lower than the device’s native resolution can improve performance and battery life.
Resolution Scaling settings for Android.
Setting | Description | |
---|---|---|
Resolution Scaling Mode | Specifies whether and how the application scales its resolution. You can set the scaling to be equal to or lower than the native screen resolution. Using a lower resolution can improve performance and battery life. | |
Disabled | Doesn’t apply resolution scaling and the application renders to the device’s native screen resolution. | |
FixedDPI | Applies resolution scaling using a target API. Use this to optimize performance and battery life or target a specific DPI setting. | |
Target DPI | The resolution of the application. If the device’s native screen DPI is higher than this value, Unity downscales the application’s resolution to match this setting. To calculate the scale, Unity uses the following: min(Target DPI * Factor / Screen DPI, 1) Where Factor is the Resolution Scaling Fixed DPI Factor from Quality settings.Note: This option only appears when you set Resolution Scaling Mode to Fixed DPI. | |
Blit A shorthand term for “bit block transfer”. A blit operation is the process of transferring blocks of data from one place in memory to another. See in Glossary Type | Controls whether to use a blit to render the final image to the screen. Using a blit is compatible with most devices but is usually slower than not using a blit. | |
Always | Unity renders to an offscreen buffer and then uses a blit to copy the contents of the buffer to the device’s framebuffer. This is compatible with most devices but is usually slower than not using blit. | |
Never | Unity renders to the framebuffer provided by the device’s operating system. If this fails, the application prints a one-time warning to the device log. This is usually faster than using blit, but it isn’t compatible with all devices. | |
Auto | Unity renders to the framebuffer provided by the device’s operating system if possible. If this fails, Unity prints a warning to the device console and uses a blit to render the final image to the screen. |
Supported Aspect Ratio
Use the Supported Aspect Ratio section to customize settings relating to which device aspect ratios to support.
Resolution Scaling settings for Android.
Setting | Description | |
---|---|---|
Aspect Ratio Mode | Specifies the largest aspect ratio the application supports. If the device’s aspect ratio is greater than this aspect ratio, Unity uses this aspect ratio for the application and adds black bars so the application doesn’t stretch.. | |
Legacy Wide Screen (1.86) | The application supports aspect ratios up to Android’s legacy wide-screen aspect ratio. | |
Native Aspect Ratio | The application supports aspect ratios up to Android’s native aspect ratio. | |
Custom | The application supports aspect ratios up to the aspect ratio you set in Up To. | |
Up To | The custom maximum aspect ratio. This setting only appears when you set Aspect Ratio Mode to Custom. |
Orientation
Use the Orientation section to customize settings relating to the orientation of the application on the device.
Orientation settings for Android.
Choose the game’s screen orientation from the Default Orientation drop-down menu:
Setting | Description | |
---|---|---|
Default Orientation | Specifies the screen orientation the application uses. Note: Unity shares the value you set for this setting between Android and iOS. | |
Portrait | The application uses portrait screen orientation where the bottom of the application’s window aligns with the bottom of the device’s screen. | |
Portrait Upside Down | The application uses portrait screen orientation where the bottom of the application’s window aligns with the top of the device’s screen. | |
Landscape Right | The application uses landscape screen orientation where the right side of the application’s window aligns with the bottom of the device’s screen. | |
Landscape Left | The application uses landscape screen orientation where the right side of the application’s window aligns with the top of the device’s screen. | |
Auto Rotation | The screen can rotate to any of the orientations you specify in the Allowed Orientations for Auto Rotation section. |
Allowed Orientations for Auto Rotation
Use the Allowed Orientations for Auto Rotation section to specify which orientations the application supports when you set Default Orientation to Auto Rotation. This is useful, for example, to lock the application to landscape orientation but allow the user to switch between landscape left and landscape right.
This section only appears when you set Default Orientation to Auto Rotation.
Allowed Orientations for Auto Rotation settings for Android.
Setting | Description |
---|---|
Portrait | Indicates whether the application supports portrait screen orientation where the bottom of the application’s window aligns with the bottom of the device’s screen. |
Portrait Upside Down | Indicates whether the application supports portrait screen orientation where the bottom of the application’s window aligns with the top of the device’s screen. |
Landscape Right | Indicates whether the application supports landscape screen orientation where the right side of the application’s window aligns with the bottom of the device’s screen. |
Landscape Left | Indicates whether the application supports landscape screen orientation where the right side of the application’s window aligns with the top of the device’s screen. |
Other
The Resolution and Presentation section also contains the following general settings.
Splash Image
Use the Virtual Reality Splash Image setting to select a custom splash image for Virtual Reality A system that immerses users in an artificial 3D world of realistic images and sounds, using a headset and motion tracking. More info
See in Glossary displays. For information on common Splash Screen settings, see Splash Screen.
Splash screen settings for virtual reality.
Below the common Splash Screen settings, you can set up an Android-specific Static Splash Image.
Splash screen settings for Android.
Setting | Description | |
---|---|---|
Image | Specifies the texture that the application uses for the Android splash screen. The standard size for the splash screen image is 320×480. | |
Scaling | Specifies how to scale the splash image to fit the devic’es screen. | |
Center (only scale down | Draws the image at its native size unless it’s too large, in which case Unity scales the image down to fit. | |
Scale to Fit (letter-boxed) | Scales the image so that the longer dimension fits the screen size exactly. Unity fills in the empty space around the sides in the shorter dimension in black. | |
Scale to Fill (cropped) | Scales the image so that the shorter dimension fits the screen size exactly. Unity crops the image in the longer dimension. |
Other Settings
This section allows you to customize a range of options organized into the following groups:
Rendering
Use these settings to customize how Unity renders your game for the Android platform.
Rendering settings for the Android platform
Property | Description | |
---|---|---|
Color Space | Choose which color space Unity uses for rendering: Gamma or Linear. See the Linear rendering overview for an explanation of the difference between the two. • Gamma: Gamma color space is typically used for calculating lighting on older hardware restricted to 8 bits per channel for the framebuffer format. Even though monitors today are digital, they might still take a gamma-encoded signal as input. • Linear: Linear color space rendering gives more precise results. When you select to work in linear color space, the Editor defaults to using sRGB sampling. If your Textures are in linear color space, you need to work in linear color space and disable sRGB sampling for each Texture. | |
Auto Graphics API | Disable this option to manually pick and reorder the graphics APIs. By default this option is enabled, and Unity tries to use Vulkan. If the device doesn’t support Vulkan, Unity falls back to GLES3.2, GLES3.1 or GLES3.0. There are three additional checkboxes to configure the minimum OpenGL ES 3.x minor version: Require ES3.1, Require ES3.1+AEP and Require ES3.2. Important: Unity adds the GLES3/GLES3.1/AEP/3.2 requirement to your Android manifest only if GLES2 is not in the list of APIs when Auto Graphics API is disabled. In this case only, your application does not appear on unsupported devices in the Google Play Store. | |
Color Gamut | You can add or remove color gamuts for the Android platform to use for rendering. Click the plus (+) icon to see a list of available gamuts. A color gamut defines a possible range of colors available for a given device (such as a monitor or screen). The sRGB gamut is the default (and required) gamut. When targeting devices with wide color gamut displays, use DisplayP3 to utilize full display capabilities. | |
Multithreaded Rendering | Enable this option to move graphics API calls from Unity�s main thread to a separate worker thread. This can help to improve performance in applications that have high CPU usage on the main thread. | |
Static Batching A technique Unity uses to draw GameObjects on the screen that combines static (non-moving) GameObjects into big Meshes, and renders them in a faster way. More info See in Glossary | Enable this option to use Static batching. | |
Dynamic Batching An automatic Unity process which attempts to render multiple meshes as if they were a single mesh for optimized graphics performance. The technique transforms all of the GameObject vertices on the CPU and groups many similar vertices together. More info See in Glossary | Enable this option to use Dynamic Batching on your build (enabled by default). Note: Dynamic batching has no effect when a Scriptable Render Pipeline is active, so this setting is only visible when nothing is set in the Scriptable Render Pipeline Asset Graphics setting. | |
Compute Skinning | Enable this option to enable DX11/ES3 GPU compute skinning, freeing up CPU resources. | |
Graphics Jobs | Enable this option to instruct Unity to offload graphics tasks (render loops) to worker threads running on other CPU cores. This is intended to reduce the time spent in Camera.Render on the main thread, which is often a bottleneck. | |
Texture compression format | Choose between ASTC, ETC2 and ETC (ETC1 for RGB, ETC2 for RGBA). See texture compression format overview for more information on how to pick the right format. See Texture compression settings for more details on how this interacts with the texture compression setting in the Build Settings. | |
Normal Map Encoding | Choose XYZ or DXT5nm-style to set the normal map encoding. This affects the encoding scheme and compression format used for normal maps. DXT5nm-style normal maps are of higher quality, but more expensive to decode in shaders. | |
Lightmap Encoding | Choose Normal Quality or High Quality to set the lightmap encoding. This setting affects the encoding scheme and compression format of the lightmaps. | |
Lightmap Streaming | Enable this option to load only the lightmap mip maps as needed to render the current game Cameras. This value applies to the lightmap textures as they are generated. Note: To use this setting, you must enable the Texture Streaming Quality setting. | |
Streaming Priority | Set the lightmap mip map streaming priority to resolve resource conflicts. These values are applied to the light map textures as they are generated. Positive numbers give higher priority. Valid values range from –128 to 127. | |
Frame Timing Stats | Enable this property to gather CPU and GPU frame time statistics. Use this together with the Dynamic Resolution A Camera setting that allows you to dynamically scale individual render targets, to reduce workload on the GPU. More info See in Glossary camera setting to determine if your application is CPU or GPU bound. | |
Virtual Texturing | Indicates whether to enable Virtual Texturing. Note: Virtual Texturing isn’t compatible with Android. | |
Shader precision model | Controls the default precision of samplers used in shaders. See Shader data types and precision for more details. | |
360 Stereo Capture | Indicates whether Unity can capture stereoscopic 360 images and videos. For more information, see Stereo 360 Image and Video Capture. Note: 360 stereoscopic capturing isn’t compatible with Android. |
Vulkan Settings
Vulkan Player settings for the Android platform
Property | Description |
---|---|
SRGB Write Mode | Enable this option to allow Graphics.SetSRGBWrite() renderer to toggle the sRGB write mode during runtime. That is, if you want to temporarily turn off Linear-to-sRGB write color conversion, you can use this property to achieve that. Enabling this has a negative impact on performance on mobile tile-based GPUs; therefore, do NOT enable this for mobile. |
Number of swapchain buffers | Set this option to 2 for double-buffering, or 3 for triple-buffering to use with Vulkan renderer. This setting may help with latency on some platforms, but in most cases you should not change this from the default value of 3. Double-buffering might have a negative impact on performance. Do not use this setting on Android. |
Acquire swapchain image late as possible | If enabled, Vulkan delays acquiring the backbuffer until after it renders the frame to an offscreen image. Vulkan uses a staging image to achieve this. Enabling this setting causes an extra blit when presenting the backbuffer. This setting, in combination with double-buffering, can improve performance. However, it also can cause performance issues because the additional blit takes up bandwidth. |
Recycle command buffers | Indicates whether to recycle or free CommandBuffers after Unity executes them. |
Apply display rotation during rendering | Enable this to perform all rendering in the native orientation of the display. This has a performance benefit on many devices. For more information, see documentation on Vulkan swapchain pre-rotation. |
Identification
Identification settings for the Android platform
Property | Function |
---|---|
Override Default Package Unity automatically pre-installs a select number of default packages (for example, the Analytics Library, Unity Timeline, etc.) when you create a new project. This differs from a bundled package because you don’t need to install it and it differs from a built-in package because it extends Unity’s features rather than being able to enable or disable them. See in Glossary Name | Indicates whether to override the default package name for your application. |
Package Name | Set the application ID, which uniquely identifies your app on the device and in Google Play Store. The basic structure of the identifier is com.CompanyName.AppName, and can be chosen arbitrarily. This setting is shared between iOS and Android. |
Version | Enter the build version number of the bundle, which identifies an iteration (released or unreleased) of the bundle. The version is specified in the common format of a string containing numbers separated by dots (eg, 4.3.2). (Shared between iOS and Android.) |
Bundle Version Code | An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. The value must be set as an integer, such as “100”. You can define it however you want, as long as each successive version has a higher number. For example, it could be a build number. Or you could translate a version number in “x.y” format to an integer by encoding the “x” and “y” separately in the lower and upper 16 bits. Or you could simply increase the number by one each time a new version is released. Keep this number under 100000 if Split APKs by target architecture is enabled. Each APK must have a unique version code so Unity adds 100000 to the number for ARMv7, and 200000 for ARM64. |
Minimum API Level | Minimum Android version (API level) required to run the application. |
Target API Level | Target Android version (API level) against which to compile the application. |
Configuration
API Compatibility Level
Script Compilation
Optimization
Optimization settings for the Android platform
Property | Description | |
---|---|---|
Prebake Collision Meshes | Enable this option to add collision data to Meshes at build time. | |
Keep Loaded Shaders Alive | When enabled, you cannot unload a shader. See Shader Loading for more information. | |
Preloaded Assets | Set an array of Assets for the player to load on startup. To add new Assets, increase the value of the Size property, then set a reference to the Asset to load in the new Element box that appears. | |
AOT compilation options | Additional options for Ahead of Time (AOT) compilation. This helps optimize the size of the built iOS player. | |
Strip Engine Code | Enable this option if you want the Unity Linker tool to remove code for Unity Engine features that your Project doesn’t use. This setting is only available with the IL2CPP scripting backend. Most apps don’t use every available DLL. This option strips out DLLs that your app doesn’t use to reduce the size of the built Player. If your app is using one or more classes that would normally be stripped out under your current settings, Unity displays a debug message when you try to build the app. | |
Managed Stripping Level | Choose how Unity strips unused managed (C#) code.The options are Disabled Low, Medium, and High. When Unity builds your app, the Unity Linker process can strip unused code from the managed DLLs your Project uses. Stripping code can make the resulting executable significantly smaller, but can sometimes accidentally remove code that is in use. For more information about these options, see documentation on Managed code stripping. For information about bytecode stripping with IL2CPP, see documentation on Managed bytecode stripping with IL2CPP. | |
Enable Internal profiler (Deprecated) | Enable this option to get the profiler data from your device in the Android SDK’s adblogcat output while testing your projects. This is only available in development builds. | |
Vertex Compression | Choose the channel that you want to set for compressing meshes under the vertex compression method, which by default, is set to Mixed. This affects all the meshes in your project. Typically, Vertex Compression is used to reduce the size of mesh data in memory, reduce file size, and improve GPU performance. For information on how to configure vertex compression and limitations of this setting, see [compressing meshes]. | |
Optimize Mesh Data | Selecting this option enables stripping of unused vertex attributes from the mesh used in a build. This reduces the amount of data in the mesh, which might help reduce build size, loading times, and runtime memory usage. However, you must remember to not change material or shader settings at runtime, if you have this setting enabled. See PlayerSettings.stripUnusedMeshComponents for more information. | |
Texture MipMap Stripping | Enable this option to enable mipmap stripping for all platforms, which strips unused mipmaps from Textures at build time. Unity determines unused mipmaps by comparing the value of the mipmap against the Quality Settings for the current platform. If a mipmap value is excluded from every Quality Setting for the current platform, then Unity strips those mipmaps from the build at build time. If QualitySettings.masterTextureLimit is set to a mipmap value that has been stripped, Unity will set the value to the closest mipmap value that has not been stripped. |
Logging
Select what type of logging to allow in specific contexts.
Logging settings for Android platform
Legacy
Enable the Clamp BlendShapes (Deprecated) option to clamp the range of blend shape weights in SkinnedMeshRenderers.
Legacy settings for the Android platform
Publishing Settings
Use the Publishing Settings to configure how Unity builds your Android app. To open the Publishing Settings, go to Edit > Project Settings, select Player, select the Android icon, and open the Publishing Settings panel.
This section describes the different parts of the Publishing Settings panel and what they do. These include:
Note: For security reasons, Unity doesn’t save your Keystore An Android system that lets you store cryptographic key entries for enhanced device security. More info
See in Glossary or Project Key passwords.
Use the Keystore Manager window to create, configure and load your keys and keystores. You can load existing keystores and keys from either the Keystore Manager or the main Android Publishing panel. If you choose to load these from inside the Keystore Manager, Unity automatically fills the Project Keystore and Project Key fields.
For further information see documentation on the Keystore Manager.
Project Keystore
A keystore is a container that holds signing keys for application security. For details, see Android developer documentation: Android keystore system.
Use the Project Keystore settings to choose which keystore to use for the open project. When you load a keystore, Unity loads all of the keys in that keystore. To load and use an existing keystore in your open project:
If you don’t have an existing keystore, leave Custom Keystore disabled.
Unity uses a debug keystore to sign your application. A debug keystore is a working keystore. It allows you to sign the application and to test it locally. However, the app store will decline apps signed in this way. This is because the app store is unable to verify the validity and ownership of the application using a debug keystore.
Property | Description |
---|---|
Custom Keystore | Enable Custom Keystore to load and use an existing Keystore. |
Select | When Custom Keystore is enabled, use this to select the keystore you want to use. The keystores below the partition in the Select dropdown are stored in a predefined dedicated location. For more details, see Choosing your keystore location. |
Path | You do not need to enter your keystore path. Unity provides this based on the keystore you choose. |
Password | Enter your keystore password to load your chosen keystore. |
Project Key
When you load a keystore, Unity loads all of the keys in that keystore. Use the Project Key settings to choose one key from that keystore to use as the active key for the open project.
Property | Description |
---|---|
Alias | Select the key you want to use for the open project. |
Password | Enter your key Password. |
Build
By default, Unity builds your application with the Android manifests, Gradle An Android build system that automates several build processes. This automation means that many common build errors are less likely to occur. More info
See in Glossary templates and Proguard files provided with the Unity installation. Use the Build section of the Android Publishing Settings to change these.
To use a custom Android manifest, Gradle template or Proguard file:
The settings in the Build section only apply to the build process for the current project.
Property | Description |
---|---|
Custom Main Manifest | Customisable version of the Android LibraryManifest.xml file. This file contains important metadata about your Android application. For further information about the responsibilities of the Main/Library Manifest see documentation on Android Manifest. |
Custom Launcher Manifest | Customisable version of the Android LauncherManifest.xml file. This file contains important metadata about your Android application’s launcher. For further information about the responsibilities of the Launcher Manifest see documentation on Android Manifest. |
Custom Main Gradle Template | Customisable version of the mainTemplate.gradle file. This file contains information on how to build your Android application as a library. For further information see documentation on Providing a custom Gradle Template. |
Custom Launcher Gradle Template | Customisable version of the launcherTemplate.gradle_ file. This file contains instructions on how to build your Android application. For further information see documentation on build.gradle templates. |
Custom Base Gradle Template | Customisable version of the baseProjectTemplate.gradle file. This file contains configuration that is shared between all other templates and Gradle projects. For further information see documentation on build.gradle templates. |
Custom Gradle Properties Template | Customisable version of the gradle.properties file. This file contains configuration settings for the Gradle build environment. This includes: — The JVM (Java Virtual Machine) memory configuration. — A property to allow Gradle to build using multiple JVMs. — A property for choosing the tool to do the minification. — A property to not compress native libs when building an app bundle. |
Custom Proguard File | Customisable version of the proguard.txt file. This file contains configuration settings for the minification process. If minification removes some Java code which should be kept, you should add a rule to keep that code in this file. For further information see documentation on Minification. |
Minify
Minification is a process which shrinks, obfuscates and optimises the code in your application. It can reduce the code size and make the code harder to disassemble. Use the Minify settings to define when and how Unity should apply minification to your build.
In most cases, it’s good practice to only apply minification to release builds, and not debug builds. This is because minification takes time, and can make the builds slower. It can also make debugging more complicated due to the optimisation that the code undergoes.
The settings in the Minify section only apply to the build process for the current project.
Property | Description |
---|---|
Use R8 | By default, Unity uses Proguard for minification. Enable this checkbox to use R8 instead. |
Release | Enable this checkbox if you want Unity to minify your application’s code in release builds. |
Debug | Enable this checkbox if you want Unity to minify your application’s code in debug builds. |
Split Application Binary
Enable the Split Application Binary option to split your output package into main (APK) and expansion (OBB) packages. The Google Play Store requires this if you want to publish applications larger than 100 MB.