Как настроить юнити под андроид



Начало разработки под 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 environment setup

To create a Unity application for Android, you first need to set up your Unity project to support Android. To support Android, a Unity project requires the following 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 :

  • The Android Build Support module.
  • The Android Software Development Kit (SDK).
  • The Native Development Kit (NDK).
  • A Java Development Kit. By default, Unity uses OpenJDK.

Before you get started, check Unity’s Requirements and compatibility documentation for Android to make sure you’re aware of any limitations for developing a Unity application for Android.

Installing dependencies

Unity distributes dependencies as modules which means you use the Unity Hub to install them. You can install them either when you install a new Unity Editor version, or add them to an existing Unity Editor install. To install modules:

The three modules to install are:

  • Android Build Support
  • Android SDK & NDK Tools
  • OpenJDK

Unity Hub displaying the three dependency modules.

Unity installs Android SDK & NDK Tools and OpenJDK respectively in the SDK , NDK , and OpenJDK folders under /Unity/Hub/Editor/[EditorVersion]/Editor/Data/PlaybackEngines/AndroidPlayer/ .

Customizing dependencies

You should use the Unity Hub to install Android SDK & NDK tools and OpenJDK to ensure that you receive the correct versions and configurations. However, there are situations where it’s useful to change the SDK, NDK, or JDK that Unity uses to build applications for Android. For example, if you have multiple versions of Unity with the same dependencies and you don’t want to duplicate the installation of the SDK, NDK, and JDK, you can specify a shared location.

To make Unity use a custom version of a dependency:

  1. Download the custom version of the dependency.
    Warning: Unity only officially supports versions of the OpenJDK, SDK, or NDK that it supplies through the Hub. For more information, see Supported dependency versions.
  2. In Unity, select Edit >Preferences (macOS: Unity >Preferences).
  3. In the left navigation column, select External Tools. The Android section of the External Tools panel contains entries for JDK, SDK, NDK, and 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
    . Each entry contains:
    • A checkbox that indicates whether to use the version that Unity provides or a custom version.
    • The path to the dependency’s installation folder.
  4. To customize the installation for any of these dependencies, disable the dependency’s respective …installed with Unity (recommended) checkbox then click Browse and select the installation folder for the custom dependency.

Supported dependency versions

This section contains information on which versions of each dependency each Unity version supports. Each version of Unity requires a specific version of the Android NDK and Android JDK, but there are no exact version requirements for the Android SDK.

Unity relies on tools that the Android SDK provides and different versions of the SDK usually have the same tools available. This means you can use any recent version of the SDK since they all contain the build tools that Unity requires.

Important: The only exceptions are Android SDK Build-tools versions higher than version 30. Unity doesn’t support Android SDK Build-tools versions higher than 30.

The following table shows the NDK version that each Unity version supports:

Unity version NDK version
2019.4 LTS r19
2020.3 LTS r19
2021.2 r21d

The following table shows the JDK version that each Unity version supports:

Unity version JDK version
2019.4 LTS 8 (OpenJDK version 1.8)
2020.3 LTS 8 (OpenJDK version 1.8)
2021.2 8 (OpenJDK version 1.8)

Setting the Android SDK Target API

The Unity Hub installs the latest version of the Android SDK Target API that Google Play requires. If you need to use a more recent version, you can change it in the Android Player Settings. To do this:

  1. Select Edit >Project Settings.
  2. In the Project settings window, select the Player tab, then open Android Player Settings:
  3. In the Other Settings section, change the Target API Level.

If you select a target API version newer than the latest installed version, the Unity Android SDK Updater can automatically download and install the new version. Unity displays a prompt and you can choose to either:

  • Automatically download and install the new version of the Android SDK.
  • Continue to use the highest installed version of the Android SDK.

If you select a target API version that isn’t installed and is older than the latest installed version, the Unity Android SDK Updater can’t perform the update and Unity displays an error message. In this case, to update the Android SDK Target API, you must use the Android sdkmanager from either Android Studio or the command-line tool. Regardless of the method you choose, make sure to select the correct Android SDK folder for Unity in the Edit > Preferences > External Tools window. For more information, see Customizing dependencies.

Important: On Windows, if you installed the Unity Editor in the default folder ( /Program Files/ ), you must run the sdkmanager with elevated privilege (Run as Administrator) to perform the update.

Chrome OS

In Unity, Chrome OS is part of the Android development environment. This means you can deliver new and existing Android applications to Chrome OS. Also, since many Chrome OS devices are laptops or have a laptop mode, you can use features such as mouse and keyboard input. For more information:

  • On Chrome OS in Unity: Chrome OS.
  • On how to build an Android application for Chrome OS: Building your Chrome OS application.

Источник

Android environment setup

To build and run for Android, you must install the Unity Android Build Support platform module. You also need to install the Android Software Development Kit (SDK) and the Native Development Kit (NDK) to build and run any code on your Android device. By default, Unity installs a Java Development Kit based on OpenJDK.

Note: Unity supports Android 4.4 “KitKat” and above. See AndroidSdkVersions for details.

1. Install Android Build Support and the Android SDK & NDK tools

Use the Unity Hub to install Android Build Support and the required dependencies: Android SDK & NDK tools, and OpenJDK.

Add Android modules

You can install Android Build Support, the Android SDK & NDK tools and OpenJDK when you install the Unity Editor, or add them at a later time.

For information on adding the Android modules:

Note: If you’re using Unity on macOS 10.15 (Catalina) and you don’t install Android tools through the Unity Hub, your operating system’s default security settings will prevent the Android NDK binaries being executed. You must either change these security settings, or download a signed Android NDK (r16b) from the Android developer website.

If you are using a 2018 version of Unity, see the Unity 2018.4 documentation for information on manually installing these dependencies.

2. Enable USB debugging on your device

To enable USB debugging, you must enable Developer options on your device. To do this, find the build number in your device’s Settings menu. The location of the build number varies between devices; for stock Android, it’s usually Settings > About phone > Build number. For specific information on your device and Android version, refer to your hardware manufacturer.

After you navigate to the build number using the instructions above, tap on the build number seven times. A pop-up notification saying “You are now X steps away from being a developer” appears, with “X” being a number that counts down with every additional tap. On the seventh tap, Developer options are unlocked.

Note: On Android versions prior to 4.2 (Jelly Bean), the Developer options are enabled by default.

Go to Settings > Developer options (or, if this does not work, on some devices the path is Settings > System > Developer options), and check the USB debugging checkbox. Android now enters debug mode when it is connected to a computer via USB.

Connect your device to your computer using a USB cable. If you are developing on a Windows computer, you might need to install a device-specific USB driver. See the manufacturer website for your device for additional information.

The setup process differs for Windows and macOS and is explained in detail on the Android developer website. For more information on connecting your Android device to the SDK, refer to the Run Your App section of the Android Developer documentation.

Customizing the Android SDK & NDK Tools and OpenJDK installation

Unity recommends that you use the Unity Hub to install Android SDK & NDK tools, to ensure that you receive the correct versions and configuration. Unity installs Android SDK & NDK Tools and OpenJDK respectively in the SDK, NDK and OpenJDK folders under /Unity/Hub/Editor/[EditorVersion]/Editor/Data/PlaybackEngines/AndroidPlayer/.

If you have multiple versions of Unity with the same required dependencies (be sure to check System requirements for the latest) and you want to avoid duplicating the installation of Android SDK & NDK Tools and OpenJDK, you can specify a shared location in the Unity Preferences window. To do this, go to Preferences > External tools and enter the directory paths in the SDK and NDK fields:

Preferences window showing external tools settings for Android

Warning: Unity does not officially support versions of the OpenJDK, SDK, or NDK other than the ones it supplies.

To change the OpenJDK, SDK Tools, or NDK that Unity uses to build Android apps:

  1. Open the Project.
  2. Open the Preferences window (Windows and Linux: Edit >Preferences; macOS: Unity >Preferences).
  3. In the left navigation column, select External Tools.

Change the OpenJDK path

  1. Uncheck JDK Installed with Unity (recommended).
  2. In the JDK field, enter the path to the JDK installation folder, or use the Browse button to locate it.

Change the Android SDK Tools path

  1. Uncheck Android SDK Tools Installed with Unity (recommended).
  2. In the SDK field, enter the path to the SDK installation folder, or use the Browse button to locate it.

Unity works with the most recent version of the Android SDK available at the time of the Unity version release.

Change the Android NDK path

  1. Uncheck Android NDK Installed with Unity (recommended).
  2. In the NDK field, enter the path to the NDK installation folder, or use the Browse button to locate it.

Each version of Unity requires a specific version of the Android NDK to be installed:

Unity version NDK version
2017.4 LTS r13b
2018.4 LTS r16b
2019.4 LTS r19
2020.1 r19
2020.2 r19
2021.1 r21d

See the System requirements page for a complete list of requirements.

Updating the Android SDK Target API

Unity Hub installs the latest version of the Android SDK Target API required by Google Play.

If you need to use a more recent version, you can change the Target API from the Target API Level field in the Player Settings window (menu: Edit > Project Settings > Player, then select the Android platform). You can find the Target API Level option in the Other Settings > Identification section.

Selecting a target API for the Android SDK

After you select an option other than the default, Unity prompts you to update the Android SDK API. You can choose to either:

  • Update the Android SDK
  • Continue to use the highest installed version of the Android SDK

Note: If you select an older version of the Target API, the Unity Android SDK Updater will not be able to perform the update and will give you this message:

Android SDK does not include your Target SDK of (version). Please use the Android SDK Manager to install your target SDK version. Restart Unity after SDK installation for the changes to take effect.

In this case, to update the Android SDK Target API, you must use the Android sdkmanager from either Android Studio or the command line tool. Regardless of the method you chose, make sure to select the correct Android SDK folder for Unity in the Edit > Preferences > External Tools window.

On Windows, if the Unity Editor is installed in the default folder ( /Program Files/ ), you must run the sdkmanager with elevated privilege (Run as Administrator) to perform the update.

Источник

You may also like...