- Настройка Android SDK
- 1. Скачать Android SDK
- 2. Установить Android SDK
- 3. Удостовериться, что система определяет ваше устройство
- 4. Добавить путь до Android SDK в Unity
- Troubleshooting Android development
- Your application crashes immediately after launch
- The game crashes after a couple of seconds when playing video
- No Android device found
- Failed to re-package resources
- Unable to merge Android manifests
- Unable to convert classes into DEX format
- Unable to install APK to device
- Решение проблем при разработке под Android
- Ошибка “No Platforms Found”:
- Unity не удаётся установить ваше приложение на ваше устройство
- Ваше приложение падает сразу после запуска.
- Building DEX Failed
- Приложение падает через несколько секунд после начала проигрывания видео.
- Моя игра закрывается, когда я жму кнопку сна
- Integrating Unity into Android applications
- How it works
- IUnityPlayerLifecycleEvents
- Limitations
Настройка Android SDK
Прежде чем вы сможете запустить написанный код на Android-устройстве, нужно выполнить несколько простых действий. Это относится как к работе с Unity, так и к созданию приложений с нуля.
1. Скачать Android SDK
Зайдите на страницу Android Developer SDK. Скачайте архив с последней версией Android SDK и распакуйте его.
2. Установить Android SDK
Следуйте инструкциям на странице Installing the SDK (причём, вы можете свободно пропустить опциональные части, относящиеся к Eclipse). В шаге 4 руководства Installing the SDK убедитесь, что добавили как минимум одну Android platform (Android платформу) с уровнем API равным или выше 9 (платформа 2.3 или выше), Platform Tools и USB drivers (USB драйверы), если вы используете Windows.
3. Удостовериться, что система определяет ваше устройство
Это может быть не так просто, особенно на Windows системах, в которых драйвера часто бывают источником проблем. Также, с вашим устройством может идти дополнительная информация или особые драйверы от производителя.
Для Windows: если Andoid устройство автоматически определяется системой, вам все равно придётся обновить драйверы на те, который поставляются с Android SDK. Это делается через диспетчер устройств Windows. —>Если устройство не определяется автоматически, используйте драйверы из Android SDK или особые драйверы, предоставленные производителем. —>Дополнительную информацию можно найти здесь: USB Drivers for Windows
Для Mac: если вы разрабатываете на OSX, тогда обычно не требуется никаких дополнительных драйверов.
Важно: Не забудьте включить “Отладку по USB” на вашем устройстве. Перейдите в Настройки -> Параметры разработчика , для включения отладки по USB. Начиная с Android Jelly Bean 4.2, параметры разработчика по умолчанию скрыты. Для их включения, понажимайте несколько раз пальцем на строку в меню Настройки -> Об устройстве -> Номер сборки . После этого вам станет доступен пункт Настройки -> Параметры разработчика .
Если вы не уверены, что ваше устройство корректно установилось в системе, пожалуйста, прочтите страницу Решение проблем при разработке под Android для дополнительной информации.
4. Добавить путь до Android SDK в Unity
При первой сборке проекта под Android (или если Unity не сможет обнаружить SDK), вас попросят указать местоположение папки, в которую вы установили Android SDK (вы должны выделить корневую папку установленного SDK). Путь до Android SDK также можно изменить в редакторе, выбрав в меню Unity > Preferences и перейдя в раздел External Tools окна настроек.
Источник
Troubleshooting Android development
While developing for Android using Unity, you could encounter a number of issues. Problems are often related to 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 or incorrect Project settings A broad collection of settings which allow you to configure how Physics, Audio, Networking, Graphics, Input and many other areas of your project behave. More info
See in Glossary . This section outlines the most common scenarios and relavant troubleshooting advice.
Your application crashes immediately after launch
Remove any native plug-ins A platform-specific native code library that is created outside of Unity for use in Unity. Allows you can access features like OS calls and third-party code libraries that would otherwise not be available to Unity. More info
See in Glossary you have.
Use adb logcat to get the crash report from your device. Consult the official Android Developer Logcat Command-Line Tool documentation for more information.
The game crashes after a couple of seconds when playing video
Ensure Settings > Developer Options > Don’t keep activities isn’t enabled on the device.
The video player is its own activity, and therefore regular game activity will be destroyed if the video player is activated.
No Android device found
If Unity cannot find an Android device connected to the system, check the following:
Make sure that your device is actually connected to your computer — check the USB cable and the sockets.
Make sure that your device has USB Debugging enabled in the Developer options. For more details, refer to the Android SDK/NDK Setup page.
Run the adb devices command from the platform-tools directory of your Android SDK installation and check the output.
If the output list is empty and you are using Windows, you may need to install the driver for 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 devices. For more details, refer to the Android SDK/NDK Setup documentation.
If the list contains entries with the unauthorized label, you may need to authorize your computer on your device and give it permission to debug it. Check the device’s screen for the corresponding dialog.
If the list contains your device with the device label, build your Project in Unity again.
Failed to re-package resources
This error occurs when the Android Asset Packaging Tool (AAPT) fails. AAPT is used to build the intermediate Asset packages A collection of files and data from Unity projects, or elements of projects, which are compressed and stored in one file, similar to Zip files, with the .unitypackage extension. Asset packages are a handy way of sharing and re-using Unity projects and collections of assets. More info
See in Glossary during Android build. This issue is most often caused by missing resources or duplicate resources in your Android plug-ins.
Check the console message for more details — it should contain the IDs of the resources that are missing or duplicates. Fix the error in your plug-ins by either adding the missing resources/settings or removing the duplicate plug-ins.
Unable to merge Android manifests
The most likely cause for this issue is that one of your plug-ins has a manifest that is incompatible with the main Unity manifest.
Check the console message for more details on which attributes are conflicting, and fix the manifests accordingly.
See the Android Manifest documentation for more details on Android manifests.
Unable to convert classes into DEX format
The most likely cause for this issue is that you have a Java plug-in added twice. This results in duplicate classes when Unity tries to build a DEX (Dalvik Executable Format) file from all the compiled Java plug-ins. Check the console output for the list of duplicate entries, and fix the plug-ins.
If your console messages says “Too many references”, it means that the number of fields and methods exceeded the DEX limit of 64k. This usually happens when the number of plug-ins or plug-in resources is too high. Due to the way the references are generated, the limit could be hit with just a couple of large plug-ins.
There are several ways to handle this issue. One of these is by stripping the plug-ins. However, the quickest way to fix it is to switch to the Gradle build system, or export the Project and build it in Android Studio.
Unable to install APK to device
This error can be caused by:
Installing to an incompatible device.
Installing to a device running a version of Android lower than the Minimum API Level in your Player settings.
Check the console for the actual error code and output.
Источник
Решение проблем при разработке под Android
Ошибка “No Platforms Found”:
- Удалите установленный Android SDK и убедитесь, что у вас нигде не установлены ещё копии.
- Обновите Java до последней стабильной версии. Никогда не забывайте, что хоть самая последняя версия не должна конфликтовать, у пользователей в прошлом всё равно бывали проблемы.
- Скачайте свежую копию самого последнего ADT Bundle и установите его следуя инструкциям. Это должно корректно откалибровать инструменты разработки: http://developer.android.com/sdk/index.html
- Настройте Unity на работу с установленным Android SDK.
Unity не удаётся установить ваше приложение на ваше устройство
- Убедитесь, что ваш компьютер видит ваше устройство и может взаимодействовать с ним. Для деталей см. Публикация сборок.
- Проверьте консоль Unity на наличие сообщений об ошибках. Это часто помогает в определении проблемы.
Если у вас появляется ошибка “Unable to install APK, protocol failure” во время сборки, то это значит, что ваше устройство подключено через USB-порт с низким питанием (возможно порт на клавиатуре или ещё на какой-нибудь периферии). Если такое случается, то попробуйте подсоединить устройство в USB порт на самом компьютере.
Ваше приложение падает сразу после запуска.
- Убедитесь, что вы не пытаетесь использовать NativeActivity с устройствами, которые это не поддерживают.
- Попробуйте убрать все нативные плагины, что у вас есть.
- Попробуйте отключить stripping.
- Используйте adb logcat чтобы получить отчёт о крахе с вашего устройства.
Building DEX Failed
Это ошибка, которая выдаёт сообщение, вроде следующего:-
Обычно это вызвано неверной версией Java на вашем компьютере. Обновление Java до последней версии обычно решает проблему.
Приложение падает через несколько секунд после начала проигрывания видео.
Убедитесь, что Settings->Developer Options->Don’t keep activities не включено на вашем телефоне. Проигрыватель видео — это отдельное приложение и поэтому обычное игровое приложение будет закрыто, если проигрыватель видео включён.
Моя игра закрывается, когда я жму кнопку сна
Измените тег activity в файле AndroidManifest.xml так , чтобы он содержал тег android:configChanges , сделайте это таким образом, как описано здесь.
Пример тега activity может выглядеть, например, вот так:-
Источник
Integrating Unity into Android applications
This page describes how to integrate the Unity Runtime Library into Android applications using the Unity as a Library feature.
You can use this feature to include Unity-powered features, such as 3D/2D Real-Time 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 , AR Augmented Reality (AR) uses computer graphics or video composited on top of a live video feed to augment the view and create interaction with real and virtual objects.
See in Glossary Experience, 3D model interaction, or 2D mini-games, into your application. The Unity Runtime Library exposes controls to manage when and how to load, activate, and unload content within the application.
Important: If you upgrade your project to Unity 2019.4 or above, the introduction of Unity as a Library might require you to adapt native and managed 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 work properly for Android. Plug-ins that make changes to 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 manifests need to use the the Gradle changes outlined in Using Unity as a library in native iOS/Android apps.
How it works
You don’t need to do anything different when you build your Gradle project from Unity.
Every Android Gradle project that Unity generates has the following structure:
- A library part in the unityLibrary module that you can integrate into any other Gradle project. This contains the Unity runtime and Player data.
- A thin launcher part in the launcher module that contains the application name and its icons. This is a simple Android application that launches Unity. You can replace this module with your own application.
To integrate Unity into another Android Gradle project, you must include the unityLibrary module of the generated Android Gradle project in your Android Unity Project through the settings.gradle file.
This repository contains example Projects and plug-ins that demonstrate how to integrate Unity into an Android app, along with further documentation.
To control a Player, relay an Intent to launch Unity activity and extend it if needed. For more information, see Android developer documentation on Intents and Intent Filters. You can also use the UnityPlayer Java API.
IUnityPlayerLifecycleEvents
IUnityPlayerLifecycleEvents provides a way to interact with two important lifecycle events of the Unity Player:
- Unload — The application calls IUnityPlayerLifecycleEvents.onUnityPlayerUnloaded when Application.Unload or UnityPlayer.unload() unloads the Unity Player. This puts the Unity Player in a paused state where it unloads all Scenes 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 , but keeps everything else loaded in the memory. - Quit — The application calls IUnityPlayerLifecycleEvents.onUnityPlayerQuitted when the Unity Player quits. The process that was running Unity ends after this call.
You can pass an instance of IUnityPlayerLifecycleEvents to the UnityPlayer constructor, or to override methods in subclasses of UnityPlayer and UnityPlayerActivity .
Limitations
Unity doesn’t control the runtime lifecycle, so Unity as a Library might not work for all possible use cases. Known limitations include:
- Unity as a Library only supports full-screen rendering, and doesn’t support rendering on part of the screen.
- You can’t load or integrate more than one instance of the Unity runtime.
- You might need to adapt third-party plug-ins (both native and managed) to work with the Unity runtime.
- Unity as a Library for Android added in 2019.3. NewIn20193
Источник