Android apps with unity

Начало разработки под Android

Разработка игр для устройств с Android OS требует подхода, схожего с разработкой под iOS. С другой стороны, аппаратное обеспечение Android-устройств не подчиняется чётким стандартам, что заставляет решать вопросы, которые отсутствуют при работе с iOS. Также присутствуют различия между версиями Unity для Android и iOS.

Подготовка среды разработки для Android

Прежде чем вы сможете протестировать свои игры на устройстве, вам нужно будет подготовить среду разработки. В частности — скачать и установить Android SDK нужной платформы и добавить ваше устройство в систему (этот процесс отличается для Windows и Mac). Об этом подробно написано на сайте Android-разработчиков, а также дополнительную информацию может предоставлять производитель вашего устройства. Так как это достаточно сложный процесс, мы приготовили небольшую инструкцию которая поможет вам подготовить всё необходимое для разработки. Если вам понадобится больше информации, вы сможете получить её на портале Android-разработчиков.

Доступ к функциям Android

Unity предоставляет API для доступа к средствам ввода и настройкам Android. Доступные классы задокументированы на странице Написание кода для Android сборок.

Привязка C, C++ или Java кода к скриптам

Unity позволяет вызывать функции, написанные на C/C++, непосредственно из скриптов (Java-функции могут быть вызваны непрямым способом). Чтобы узнать как из Unity получать доступ к функциям из нативного кода, посетите страницу о сборке плагинов для Android.

Occlusion Culling (отсечение невидимой геометрии)

Unity предоставляет поддержку occlusion culling, что очень полезно при оптимизации для мобильных платформ. Больше информации можно найти на странице Occlusion culling.

Настройка начальной заставки

Заставка, отображаемая при запуске игры, может быть настроена — см. эту страницу для дополнительной информации.

Решение проблем и сообщения об ошибках

Существует множество причин, из-за которых ваше приложение вылетает или не работает должным образом. Наше руководство по решению специфических для Android проблем поможет вам разобраться с причинами ошибок в кратчайшие сроки. Если после прочтения руководства вы предполагаете, что проблема именно в Unity — вам следует составить сообщение об ошибке. Обратитесь к этой странице за инструкциями.

Как Unity для Android отличается от версии для настольных компьютеров

JavaScript со строгой типизацией

Для улучшения производительности в Android-версии Unity динамическая типизация в JavaScript всегда отключена (как если бы к каждому скрипту автоматически применялась #pragma strict). Это важно помнить, если вы переносите на Android проект со старших платформ, и если вы столкнётесь с ошибками компиляции — проблему стоит искать в первую очередь в типизации. С такими ошибками обычно легко справиться, убедившись что типы всех переменных явно указаны или приведёны при инициализации.

ETC — рекомендуемый способ сжатия текстур

Хоть Unity Android и поддерживает DXT/PVRTC/ATC текстуры, Unity распакует текстуры в формат RGB(A) при выполнении, если эти методы сжатия на поддерживаются на конкретном устройстве. Это может серьёзно повлиять на производительность GPU отрисовки, потому рекомендуется использовать формат ETC. Он является фактическим стандартом для Android, и должен поддерживаться всеми современными устройствами. С другой стороны, ETC не поддерживает альфа-канал, и иногда 16-битные RGBA текстуры будут лучшим выбором по критериям качества, размера и скорости рендеринга там, где нужен альфа-канал.

Также возможно создать несколько дистрибутивов игры (apk-файлов) с разными форматами текстур, чтобы Android Market сам предоставлял для каждого устройства наиболее подходящий из дистрибутивов. За подробностями обратитесь к этой странице.

Проигрывание видео.

Видео текстуры (MovieTexture) не поддерживаются на Android, но программно доступно полноэкранное поточное проигрывание. Для дополнительной информации о поддерживаемых форматах файлов и API скриптинга, ознакомьтесь со страницой класса MovieTexture или со страницей поддерживаемых на Android форматах медиа.

Источник

Android

This section of the User Manual contains documentation on developing for the Android platform,

Environment setup

Before you can run code on your Android device or an Android emulator, you must set up Unity to support Android development. See Android environment setup.

If you don’t install one or more necessary components during initial setup, Unity prompts you to download missing components when you try to build a Project for Android.

Building your app

Unity lets you configure build and runtime settings for your app. See Building apps for Android.

If you have a Unity Pro subscription, you can customize the splash screen that displays when the game launches. See Customizing an Android splash screen.

Scripting

Unity provides scripting APIs that allow you to access input data and other settings from Android devices. See Android scripting.

You can use plug-ins A set of code created outside of Unity that creates functionality in Unity. There are two kinds of plug-ins you can use in Unity: Managed plug-ins (managed .NET assemblies created with tools like Visual Studio) and Native plug-ins (platform-specific native code libraries). More info
See in Glossary to call Android functions written in C/ C++ directly from C# scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary . You can also call Java functions indirectly. See Building and using plug-ins for Android.

Читайте также:  Привязка карт для oziexplorer андроид

Optimization

Unity includes support for occlusion culling A feature that disables rendering of objects when they are not currently seen by the camera because they are obscured (occluded) by other objects. More info
See in Glossary , which disables rendering The process of drawing graphics to the screen (or to a render texture). By default, the main camera in Unity renders its view to the screen. More info
See in Glossary of objects when they’re not currently seen by the camera A component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary because they’re obscured (occluded) by other objects. This is a valuable optimization method for mobile platforms. See Occlusion culling.

Troubleshooting and bug reports

The Android troubleshooting guide helps you discover the cause of bugs as quickly as possible. If, after consulting the guide, you suspect the problem is being caused by Unity, file a bug report following the Unity bug reporting guidelines.

Texture compression

Ericsson Texture Compression 3D Graphics hardware requires Textures to be compressed in specialized formats which are optimized for fast Texture sampling. More info
See in Glossary (ETC) is the standard texture compression A method of storing data that reduces the amount of storage space it requires. See Texture Compression, Animation Compression, Audio Compression, Build Compression.
See in Glossary format on Android.

ETC1 is supported on all current Android devices, but it does not support textures that have an alpha channel. ETC2 is supported on all Android devices that support OpenGL ES 3.0. It provides improved quality for RGB textures, and also supports textures with an alpha channel.

By default, Unity uses ETC1 for compressed RGB textures and ETC2 for compressed RGBA textures. If ETC2 is not supported by an Android device, the texture is decompressed at run time. This has an impact on memory usage, and also affects rendering speed.

DXT, PVRTC, ATC, and ASTC are all support textures with an alpha channel. These formats also support higher compression rates and/or better image quality, but they are only supported on a subset of Android devices.

It is possible to create separate Android distribution archives (.apk) for each of these formats and let the Android Market’s filtering system select the correct archives for different devices.

Movie/Video playback

We recommend you use the Video Player to play video files. This supersedes the earlier Movie Texture feature.

Known video compatibility issues

Not all devices support resolutions greater than 640 × 360. Runtime checks verify device support and don’t play the movie if there’s a failure.

For Android Lollipop (5.0 and 5.1.1) and above, you can use any resolution or number of audio channels, provided the target device supports them.

Unity supports playback from asset bundles for uncompressed bundles, read directly from disk.

Playback support for compressed asset bundles is available for Android 9 and later.

Format compatibility issues are reported in the adb logcat output and are always prefixed with AndroidVideoMedia .

Watch for device-specific error messages located near the error messages in Unity: they’re not available to the engine, but often explain what the compatibility issue is.

Источник

Building apps for Android

There are two locations to configure settings that affect how your app is built:

  • Player settings Settings that let you set various player-specific options for the final game built by Unity. More info
    See in Glossary — Allows you to configure runtime settings for the app. For more information on Player settings, see Player settings for the Android platform.
  • Build settings — Allows you to configure build system parameters and build the app.

The output package includes an APK, and an APK expansion file (OBB) if the Split Application Binary option is selected in the Player settings. For more information on OBB files, see OBB Support.

To optimize for download and installation size, enable the Split APKs by target architecture option in the Player settings. The Split APKs by target architecture option produces one set of APKs and OBBs for each device architecture selected in the Target Architecture list in the Player settings. You can upload this set of APKs (and OBBs, if enabled) to the Google Play, or other, store instead of a FAT APK in which all of the selected architectures are included into a single APK. For more information on this feature, see Multiple APK support on the Android Developer website.

Configuring Build Settings

To configure and build apps for Android, access the Build Settings window, select File > Build Setting. In Platforms, select Android.

To set Android as your default build platform, click the Switch Platform button.

When you have specified your build settings, click the 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 button to create your build. To build the app, click Build And Run to create and run your build on the platform you have specified. In Platform, select Android.

Читайте также:  Dr web pro android apk
Option Purpose
Texture Compression The Unity Android build system supports the following texture compression A method of storing data that reduces the amount of storage space it requires. See Texture Compression, Animation Compression, Audio Compression, Build Compression.
See in Glossary format options: Don’t override, DXT (Tegra), PVRTC PowerVR Texture Compression (PVRTC) is a fixed-rate texture format that compresses textures to significantly reduce file sizes without causing a noticeable reduction in image quality. More info
See in Glossary (PowerVR), ETC (default), ETC2 (GLES 3.0), and ASTC Adaptive Scalable Texture Compression (ASTC) A block-based texture format that compresses textures to significantly reduce file sizes without cau sing a noticable reduction in image quality. More info
See in Glossary . For advice on using these formats, see the Texture Compression section.
ETC2 fallback 32-bit, 16-bit, and 32-bit, half resolution.
Build System
Internal (deprecated) — Generate the output package (APK) using the internal Unity build process, based on Android SDK utilities. Selecting Internal hides the Export Project checkbox.
Gradle — Generate the output package (APK) using the Gradle build system. Supports direct Build and Run and exporting the Project to a directory. This is the default Build System for Unity.
Export Project Export the Project as a Gradle project that you can import into Android Studio.
Build AppBundle (Google play) Build an Android App Bundle for distribution on Google Play.
Run Device A drop-down list of attached devices on which you can test your build. If you connect a new device or or you don’t see an attached device in the list, click the Refresh button to reload the list.
Development Build A development build includes debug symbols and enables the 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 . Selecting Development Build allows you to select the Autoconnect Profiler, Script Debugging, and Scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary Only Build options.
Autoconnect Profiler Allows the Profiler to automatically connect to the build. Selectable when the Development Build option is selected. For more information on the Profiler, see Profiler Overview.
Script Debugging Allow script debuggers to attach to the Player remotely. Enabled when the Development Build option is selected.
Scripts Only Build Check this option to build just the scripts in the current Project. Enabled when the Development Build option is selected.
Compression Method Compress the data in your Project at build time. Choose between the following methods:
Default — The default compression is ZIP, which gives slightly better compression results than LZ4 and LZ4HC, but data is slower to decompress.
LZ4 — A fast compression format that is useful for development builds. Using LZ4 compression can significantly improve loading time of games/apps built with Unity. For more information, see BuildOptions.CompressWithLz4.
LZ4HC — A high compression variant of LZ4 that is slower to build but produces better results for release builds. Using LZ4HC compression can significantly improve loading time of games/apps built with Unity. For more information, see BuildOptions.CompressWithLz4HC.
SDKs for App Stores Select which third party app stores to integrate with. To include an integration, click Add next to an App Store name. The Unity Package Manager automatically downloads and includes the relevant integration package.

Texture compression

Unity uses the Ericsson Texture Compression (ETC) format for textures that don’t have individual texture format A file format for handling textures during real-time rendering by 3D graphics hardware, such as a graphics card or mobile device. More info
See in Glossary overrides. When building an APK to target specific hardware, use the Texture Compression 3D Graphics hardware requires Textures to be compressed in specialized formats which are optimized for fast Texture sampling. More info
See in Glossary option to override this default behavior. Texture Compression is a global setting for the Project. If a texture has a specific override on it, that texture is not affected by the Texture Compression setting. For additional information, see Textures An image used when rendering a GameObject, Sprite, or UI element. Textures are often applied to the surface of a mesh to give it visual detail. More info
See in Glossary .

For additional information on textures and texture compression, see Android 2D Textures Overrides.

For additional information on the texture compression formats, see Texture compression formats for platform-specific overrides. In particular, see the Notes on Android at the end of the topic.

Note: Texture Compression is a global setting. Individual textures override the global setting.

ETC2 fallback

For Android devices that don’t support ETC2 (which don’t support GL ES3), you can override the default ETC2 texture decompression by choosing from 32-bit, 16-bit, or 32-bit with half the resolution formats.

This option allows you to choose between the uncompressed image quality and the amount of memory the uncompressed texture occupies. 32-bit RGBA texture is the highest quality format, and takes twice the required disk space as the 16-bit format, but a texture in 16-bit might lose some valuable color information. 32-bit half-resolution reduces the memory requirement further, but the texture is likely to become blurry.

Build system

Unity supports two Android build systems: 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 and Internal.

The steps involved with building for Android are:

Preparing and building the Unity Assets Any media or data that can be used in your game or Project. An asset may come from a file created outside of Unity, such as a 3D model, an audio file or an image. You can also create some asset types in Unity, such as an Animator Controller, an Audio Mixer or a Render Texture. More info
See in Glossary .

Processing the plug-ins A set of code created outside of Unity that creates functionality in Unity. There are two kinds of plug-ins you can use in Unity: Managed plug-ins (managed .NET assemblies created with tools like Visual Studio) and Native plug-ins (platform-specific native code libraries). More info
See in Glossary .

Splitting the resources into the parts that go to the APK and the OBB, if Split Application Binary is selected.

Building the Android resources using the AAPT utility (internal build only.)

Generating the Android manifest.

Merging the library manifests into the Android manifest (internal build only.)

Compiling the Java code into the Dalvik Executable format (DEX) (internal build only.)

Building the IL2CPP A Unity-developed scripting back-end which you can use as an alternative to Mono when building Projects for some platforms. More info
See in Glossary library, if IL2CPP Scripting Backend is selected.

Building and optimizing the APK and OBB packages.

Gradle build system

The Gradle build system uses Gradle to build an APK or export a Project in Gradle format, which can then be imported to Android Studio. When you select this build system, Unity goes through the same steps as the Internal build system excluding resource compilation with AAPT, merging manifests, and running DEX. Unity then generates the build.gradle file (along with the other required configuration files) and invokes the Gradle executable, passing it the task name and the working directory. Finally, the APK is built by Gradle.

Internal build system

The Internal build system creates an APK using the Android SDK utilities to build and optimize the APK and OBB packages. For more information about OBB files, see OBB Support.

Exporting the Project

If you need more control over the build pipeline, or to make changes that Unity does not normally allow (for example, fine tuning the manifest files that are automatically generated by Unity), you can export your Project and import it into Android Studio. Exporting a Project is only available when you have selected Gradle as your Build System.

To export the Project:

  1. From the Build System drop-down menu, select Gradle.
  2. Check the Export Project checkbox. When Export Project is checked, the Build button is relabeled Export and the Build And Run button is disabled.
  3. Click the Export button and select a destination folder for the roject.

When the export finishes, open Android Studio and import your project. For more information on importing projects to Android Studio, see the Migrate to Android Studio section of the Android Developer documentation.

Build or Build and Run

The Build Settings window offers two options: Build and Build and Run. Using either option saves the output packages (APK and OBB, if enabled) to the path that you select. You can publish these packages to the Google Play Store, or install them on your device manually with the help of Android Debug Bridge (ADB). For further information about installing apps manually, see the Run your app section of the Android Developer documentation. For information on ADB An Android Debug Bridge (ADB). You can use an ADB to deploy an Android package (APK) manually after building. More info
See in Glossary commands, see the Android Debug Bridge section of the Android Developer documentation.

Selecting Build and Run saves the output packages to the file path you specify, while also installing your app on the Android device connected to your computer.

If the Split Application Binary option is enabled, the OBB file is pushed to the correct location on your device. If Development Build A development build includes debug symbols and enables the Profiler. More info
See in Glossary is checked, Unity also sets up a Profiler tunnel and enables CheckJNI. After that, the app is launched. The Split Application Binary setting is located in the Publishing Settings section of the Player settings.

Tip: Specify the output path for the packages and then use the Ctrl+B (Windows) or Cmd+B (macOS) keyboard shortcut to Build and Run using the saved output path.

2018–11–19 Page amended

Updated functionality in 5.5

Updated the Build Settings Configuration options

Источник

Читайте также:  Отдам все для андроида
Оцените статью