unity minify что такое

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 versionGradle version
2020.3 starting from 2020.3.15f16.1.1
2020.1, 2020.2, 2020.3 up to and including 2020.3.14f15.6.4
2019.45.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.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое

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.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое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:
DEPSList of project dependencies In the context of the Package Manager, a dependency is a specific package version (expressed in the form package_name@package_version ) that a project or another package requires in order to work. Projects and packages use the dependencies attribute in their manifests to define the set of packages they require. For projects, these are considered direct dependencies; for packages, these are indirect, or transitive, dependencies. More info
See in Glossary ; that is, the libraries that the Project uses.
APIVERSIONAPI version to build for (for example, 25).
MINSDKVERSIONMinimum API version (for example, 25).
BUILDTOOLSSDK Build tools used (for example, 25.0.1).
TARGETSDKVERSIONAPI version to target (for example, 25).
APPLICATIONIDAndroid Application ID (for example, com.mycompany.myapp).
MINIFY_DEBUGEnable minify for debug builds (true or false).
PROGUARD_DEBUGUse proguard for minification in debug builds (true or false.)
MINIFY_RELEASEEnable minify for release builds (true or false).
PROGUARD_RELEASEUse proguard for minification in release builds (true or false).
USER_PROGUARDCustom user proguard file (for example, proguard-user.txt ).
SIGNComplete the signingConfigs section if this build is signed.
SIGNCONFIGSet to signingConfig signingConfig.release if this build is signed.
DIR_GRADLEPROJECTThe directory where Unity creates the Gradle project.
DIR_UNITYPROJECTThe 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: Сборка под Android или «размер имеет значение»

В некоторых случаях необходимо работать над снижением размера сборки для Андроид. Например, установка тяжеловесных APK для пользователей мобильного интернета может влететь в копеечку. Превышение размера APK в 50 Мб в Google Play выливается в дополнительные трудности при аплоаде.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое

Мы разрабатывали под Андроид на Unity 2D-игру, которая изобилует картинками (большинство с областями прозрачности) и разнообразными звуками, и столкнулись с проблемой размера APK. Забегая вперед скажу, что решив ее и снизив вес в 1,5 раза, мы получили в 1,5 раза больше скачиваний. Заставляет задуматься, не правда ли?

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

Другую полезную информацию по данному вопросу в интернете мы практически не нашли. Потому провели небольшое исследование, результатами которого спешим с вами поделиться.

ИЗОБРАЖЕНИЯ

Уточним насчёт изображений. В нашей игре соблюдается принцип pixel-perfect. Все изображения без альфа-канала имеют плавный градиент. Остальные изображения с прозрачностью, а непрозрачные области тоже имеют плавный градиент.

Проанализируем, какой вклад в размер АРК вносят изображения в формате PNG и JPG.

Картинки в формате PNG

Далее мы сохранили первую картинку в Photoshop с настройками: Compression->None/Fast, Intrelaced: Yes. Получили файл размером 9000 Кбайт, однако в сборку он добавил те же 236 Кбайт.

Это подтверждает слова из документации, о том, что Unity перекодирует все ассеты во внутренний формат. Очевидно, он приблизительно соответствует формату PNG, сохранённому в фотошопе с настройками: Compression->Smallest/Slow, Intrelaced: No. И Unity перекодирует все PNG в этот формат, независимо от начального формата файла.

Картинки в формате JPG

Опыты однозначно показали, что изображения JPG вносят вклад в размер сборки пропорционально своему размеру. Пока не совсем понятно, как ведёт себя Unity в случае, если ассет находится в формате JPG. Мы сохранили ту же самую (первую) картику в JPG и получили очень маленький файл на файловой системе (75 Кбайт). Однако в сборке он занял непомерных 767 Кбайт (*).

Мы проводили эксперимент на большом количестве разных картинок, здесь я привожу лишь малую часть исследований. В других экспериментах нам наоборот удавалось снизить общий размер сборки конвертированием всех файлов из PNG в JPG.
Причин этого явления выявить пока не удалось.
Скорее всего, снова имеет место внутренний формат Unity, однако точные принципы взаимодействия колдовского механизма Unity с ассетами JPG выяснить пока не удалось.

Еще один способ работы с JPG будет описан ниже.

ЗВУКИ

Для звуков значение имеют две настройки импорта: Audio Format и ForceToMono.

Файлы в формате WAV занимают больше места в сборке, чем файлы в формате MP3 (вклад в размер сборки приблизительно равен размеру файла). Стерео WAV файл займёт меньше места, если выставить ForceToMono = true. Точно такого же эффекта можно достичь, если конвертировать файл в «моно» ещё до импорта (тогда ForceToMono не будет доступна в инспекторе).

Однако если для файла WAV установить настройку импорта AudioFormat = Compressed, то в сборке он займёт места столько же, сколько и соответствующий MP3 файл высшего качества (Audacity: variable bitrate, 220-260 kbps). То есть Unity самостоятельно кодирует звук в формат MP3.

Для файлов в одинаковом формате действует принцип прямо пропорционального вклада в размер сборки.

Остальные настройки импорта на размер сборки никак не влияют. Они влияют на количество места, занимаемое звуком в RAM.

А ТЕПЕРЬ О КОНКРЕТНЫХ ШАГАХ К НАШЕЙ ЦЕЛИ

Таким образом, совет: для снижения нагрузки на ОЗУ
* избегать больших областей прозрачности в изображениях;
* не формировать атласы с большими участками прозрачности, особенно в NGUI.

(Но это мы отвлеклись от основной темы.)

Несколько слов о dll

Документ приводит список обязательно включаемых в сборку dll и призывает минимизировать количество дополнительных dll (особенно тяжёлых). В частности, по возможности не использовать System.dll (добавляет к APK 2 Мбайт). Однако даже если мы будем избегать ссылок на методы из этой библиотеки, System.dll всё равно (по состоянию на Unity 4.5.5) включается в сборку, так как её подтягивает обязательная Mono.Security.dll. Потому, получается, что официальная документация Unity в этом месте не совсем релевантна.

А вот использования других (необязательных) dll желательно избегать во имя снижения размера сборки.

На сегодня у нас всё. Спасибо за внимание!

(Просьба рассматривать данный материал как более-менее систематизированные результаты исследования, а не как универсальное руководство к действию. Буду очень рад комментариям, замечаниям, конструктивной критике, возражениям, предложениям, дополнениям. И, конечно, несказанно рад буду узнать, какие приёмы применяют коллеги из других компаний для решения обсуждаемого вопроса.)

Источник

Пишем плагин для Unity правильно. Часть 2: Android

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое

В предыдущей части мы рассмотрели основные проблемы написания нативных плагинов на 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. Иначе каждая последующая интеграция будет ломать предыдущие и отнимать все больше времени.

Источник

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. Закомментируем или удалим строки:

Окончательный вид файла:

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое

Инициализация Multidex

Если минимальный уровень API Android, установленный на 20 или ниже.

Обновите файл манифеста, расположенный в Assets/Plugins/Android/AndroidManifest.XML. Если у вас нет этого файла, вам придется его создать. Вы можете найти AndroidManifest по умолчанию.xml в месте установки Unity. Но вам также придется вручную применить параметры проекта вашего приложения: имя пакета, разрешения, параметры конфигурации и другую информацию.

Если вы только что создали новый файл манифеста или у вас уже был он, вы просто добавляете этот параметр(android:name) следующим образом:

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое

На этом все. Ошибка исчезнет, и вы спокойно сбилдите свой проект.

Источник

Android Player settings

This page details the Player settings specific to the Android platform. For a description of the general Player settings, see the Player settings.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеAndroid Player settings

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 :

Resolution and Presentation

Use the Resolution and Presentation section to customize aspects of the screen’s appearance.

Other Resolution and Presentation properties are grouped under these sections:

Resolution Scaling

Supported Aspect Ratio

Set the Aspect Ratio Mode for the device. You can choose from Legacy Wide Screen (1.86), Native Aspect Ratio, and Custom. When you choose Custom, the Up To field appears.

Set a custom maximum screen width with the Up To property. This property is only available when Aspect Ratio Mode is set to Custom.

Orientation

Choose the game’s screen orientation from the Default Orientation drop-down menu:

SettingFunction
PortraitHome button appears at the bottom.
Portrait Upside DownHome button appears at the top.
Landscape LeftHome button appears on the right side.
Landscape RightHome button appears on the left side.
Auto RotationAllow the screen to automatically rotate to any of the orientations specified by the Allowed Orientations for Auto Rotation settings. This is the default.

Note: This setting is shared between iOS Apple’s mobile operating system. More info
See in Glossary and Android devices.

When you set the orientation to Auto Rotation, the Allowed Orientations for Auto Rotation section appears.

Allowed Orientations for Auto Rotation

This section is only visible when Default Orientation is set to Auto Rotation.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеAllowed Orientations for Auto Rotation Player settings for the Android platform

Because Auto Rotation changes screen orientation to match the device, you may want to limit the screen orientations allowed (for example, locking a device to landscape).

Enable each orientation you want to allow by checking its box in this section:

SettingFunction
PortraitAllow portrait orientation.
Portrait Upside DownAllow portrait upside-down orientation.
Landscape RightAllow landscape right orientation (home button on the left side).
Landscape LeftAllow landscape left orientation (home button is on the right side).

Other

Splash Image

Above the common Splash Screen settings, you can use the Virtual Reality Splash Image setting to specify 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.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеSplash Settings for the Android platform Player

Below the common Splash Screen settings, you can set up an Android-specific Static Splash Image.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеUse Storyboard for Launch Screen on the Android Player platform

Use the Android Splash Screen property to specify the texture that should be used for the Android splash screen. The standard size for the splash screen image is 320×480.

Choose how you want Unity to scale the splash image to fit the device’s screen from the Splash Scaling drop-down menu. The options are:

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.

Vulkan Settings

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеVulkan Player settings for the Android platform

PropertyFunction
SRGB Write ModeEnable this option to allow Graphics.SetSRGBWrite() on Vulkan renderer to toggle the sRGB write mode during the frame. Enabling this has a negative impact on performance.
Number of swapchain buffersSet this option to 2 for double-bufferin, or 3 for triple-buffering. Double-buffering might have a negative impact on performance.
Acquire swaichain image late as possibleEnable this option to acquire the backbuffer image right before the image is presented. This might improve performance if double-buffering is selected, but should otherwise be avoided on Android because it introduces additional memory bandwidth costs.
Apply display rotation during renderingEnable 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

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеIdentification settings for the Android platform

PropertyFunction
Package NameSet 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.
VersionEnter 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 CodeAn 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 LevelMinimum Android version (API level) required to run the application.
Target API LevelTarget Android version (API level) against which to compile the application.

Configuration

API Compatibility Level

Script Compilation

Optimization

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеOptimization settings for the Android platform

SettingFunction
Prebake Collision A collision occurs when the physics engine detects that the colliders of two GameObjects make contact or overlap, when at least one has a Rigidbody component and is in motion. More info
See in Glossary Meshes
Enable this option to add collision data to Meshes at build time.
Keep Loaded Shaders AliveEnable this option to prevent shaders from being unloaded.
Preloaded AssetsSet an array of Assets for the player to load on startup.
To add new Assets, increase the value of the Size property and then set a reference to the Asset to load in the new Element box that appears.
Strip Engine Code (IL2CPP only)Specify whether the Unity Linker tool removes code for Unity Engine features that your Project doesn’t use.
Managed Stripping LevelDefines how aggressively Unity strips unused managed (C#) code.
When Unity builds your game or application, the Unity Linker process can strip unused code from the managed dynamically linked libraries used in the project. Stripping code can make the resulting executable significantly smaller, but can sometimes mistakenly remove code that is actually used. This setting allows you to choose how aggressively Unity should remove unused code.
Disabled (Mono only)Do not strip any code. (Managed code stripping is always enabled when using IL2CPP.)
NormalRemove unreachable managed code to reduce build size and Mono/IL2CPP build times.
Aggressive (Experimental)Remove code more aggressively than under the Normal option. Code size is further reduced, but this additional reduction may have side effects. For example, some methods may no longer be visible in the debugger and code accessed through reflection can be stripped. You can create a custom link.xml file to preserve specific classes and methods. See Managed bytecode stripping with IL2CPP for more information.
Enable Internal profiler A window that helps you to optimize your game. It shows how much time is spent in the various areas of your game. For example, it can report the percentage of time spent rendering, animating, or in your game logic. More info
See in Glossary (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.
Script Call OptimizationChoose how to optionally disable exception handling for a speed boost at runtime. See iOS Optimization for details.
Slow and SafeUse full exception handling (with some performance impact on the device when using the Mono scripting backend).
Fast but no ExceptionsNo data provided for exceptions on the device (the game runs faster when using the Mono scripting backend).
Note: If you use this option with the IL2CPP Scripting Backend it won’t impact performance; however, using it can avoid undefined behavior on release builds.
Vertex CompressionSet vertex compression per channel. For example, you can enable compression for everything except positions and lightmap UVs. Whole Mesh The main graphics primitive of Unity. Meshes make up a large part of your 3D worlds. Unity supports triangulated or Quadrangulated polygon meshes. Nurbs, Nurms, Subdiv surfaces must be converted to polygons. More info
See in Glossary compression set per imported object overrides where vertex compression is set on objects. Everything else obeys these vertex compression settings.
Optimize Mesh DataEnable this option to remove any data from Meshes that is not required by the Material applied to them (such as tangents, normals, colors, and UVs).

Logging

Select what type of logging to allow in specific contexts.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеLogging settings for Android platform

Legacy

Enable the Clamp BlendShapes (Deprecated) option to clamp the range of blend shape weights in SkinnedMeshRenderers.

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такое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:

Project Keystore
Project Key
Build The process of compiling your project into a format that is ready to run on a specific platform or platforms. More info
See in Glossary
Minify
Split Application Binary

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеAndroid publishing panel

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.

PropertyDescription
Custom KeystoreEnable Custom Keystore to load and use an existing Keystore.
SelectWhen 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.
PathYou do not need to enter your keystore path. Unity provides this based on the keystore you choose.
PasswordEnter 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.

PropertyDescription
AliasSelect the key you want to use for the open project.
PasswordEnter 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.

PropertyDescription
Custom Main ManifestCustomisable 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 ManifestCustomisable 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 TemplateCustomisable 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 TemplateCustomisable 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 TemplateCustomisable 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 TemplateCustomisable 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 FileCustomisable 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.

PropertyDescription
Use R8By default, Unity uses Proguard for minification. Enable this checkbox to use R8 instead.
ReleaseEnable this checkbox if you want Unity to minify your application’s code in release builds.
DebugEnable 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.

XR Settings

unity minify что такое. Смотреть фото unity minify что такое. Смотреть картинку unity minify что такое. Картинка про unity minify что такое. Фото unity minify что такоеXR Settings for the Android Player

SettingFunction
Virtual Reality SupportedEnable this if your application is a virtual reality application, then add the required VR SDKs to the list.
Virtual Reality SDKsAdd and remove Virtual Reality SDKs from the list. This list is only available when the Virtual Reality Supported is enabled.
To add an SDK to the list, click the plus (+) button.
To remove an SDK from the list, select it and then click the minus (-) button.
Some of the SDKs provide extra settings that appear here. For details, see XR SDKs.
Stereo Rendering ModeChoose how you want to render for a virtual reality device.
Multi PassThis is the normal rendering mode. Unity renders 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 twice: first to render the left-eye image; and then again for the right-eye image.
Single Pass Multiview or Instanced (Preview)Render both eye images at the same time into one packed Render Texture. This means that the whole Scene is only rendered once, which significantly reduces CPU processing time.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *