- Android mobile scripting
- Accessing device-specific features and properties
- Vibration support
- Activity indicator
- Anti-piracy check
- Screen orientation
- Android
- Environment setup
- Building your app
- Scripting
- Optimization
- Troubleshooting and bug reports
- Texture compression
- Movie/Video playback
- Known video compatibility issues
- Integrating Unity into Android applications
- How it works
- IUnityPlayerLifecycleEvents
- Limitations
- Unity3D — написание плагинов для Android
- Предисловие
- Что нам понадобится
- Исходники
- Android
- Unity3D
Android mobile scripting
Note: For cross-platform Projects, use the UNITY_ANDROID #define directive to conditionally compile Android-specific C# code. See documentation on Platform dependent compilation to learn more.
Accessing device-specific features and properties
Apps can access most features of an Android device through the Input and Handheld classes. For more information, see:
Vibration support
You can trigger a vibration by calling Handheld.Vibrate. Devices without vibration hardware ignore this call.
Activity indicator
Mobile operating systems have built-in activity indicators your app can use during slow operations. For more information, see Handheld.StartActivityIndicator.
To access device-specific properties, use these 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 :
Script | Device property |
---|---|
SystemInfo.deviceUniqueIdentifier | Always returns the md5 of ANDROID_ID . For more information, see Android developer documentation on ANDROID_ID. |
SystemInfo.deviceName | Returns the device name. For Android devices, Unity tries to read device_name and bluetooth_name from secure system settings. If these strings have no values, Unity returns . |
SystemInfo.deviceModel | Returns the device model. This often includes the manufacturer name and model number (for example, “LGE Nexus 5 or ”SAMSUNG-SM-G900A»). |
SystemInfo.operatingSystem | Returns the operating system name and version. |
Anti-piracy check
To get licensing information about users and prevent piracy, Google offers a service called Google Play Application Licensing. See the Google Play Application License Verification example plug-in 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 on the Asset Store A growing library of free and commercial assets created by Unity and members of the community. Offers a wide variety of assets, from textures, models and animations to whole project examples, tutorials and Editor extensions. More info
See in Glossary for an example of how you can integrate this functionality into your Unity application. You can also download the plug-in source code from its GitHub repository.
Screen orientation
You can control the screen orientation of your application on both iOS Apple’s mobile operating system. More info
See in Glossary and Android devices. Detecting a change in orientation or forcing a specific orientation is useful for creating game behaviors that depend on how the user is holding the device.
Источник
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.
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.
Источник
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
Источник
Unity3D — написание плагинов для Android
Предисловие
Здравствуйте!
Тут находятся инструкции, как расширить возможности Unity3D в работе с Android-приложениями. Другими словами, мы можем в Eclipse виде библиотеки на языке программирования Java написать нужный функционал для Android, экспортировать его в .jar и использовать в Unity3D. В основном пишут то, что отсутствует в возможностях Unity3D — такие вещи, как включение/выключение фонарика или длительная вибрация
Что нам понадобится
- Установленные Android SDK и Eclipse (либо другая IDE на ваш выбор и усмотрение)
- Минимальные познания в Java и C#
- Немного терпения
Исходники
Android
Написание библиотеки Android для Unity3D ничем не отличается от написания обычной библиотеки Android для чего бы то ни было. Только для начала работы надо взять еще библиотеку специально для этого от Unity — для этого идем в папку, где у нас она установлена (обычно C:/ProgramFiles), далее идем по такому пути Unity\Editor\Data\PlaybackEngines\androidplayer\bin\classes.jar, и копируем библиотеку в удобное для вас место.
Создаем проект в Eclipse: жмем «File» — «Project» — «Android Application Project» — «Next», после чего вводим название объекта. Допустим, нам надо написать проект, который может включать и выключать лампочку Android-устройства (такой функции в Unity3D изначально нет). Тогда называем проект UnityTorch. Package Name у проекта пусть будет com.izaron.habr.unitytorch. После чего несколько раз нажимаем «Next», пока не дойдем до имени нашего activity. Называем его UnityTorchActivity (от этого зависит имя главного класса), после чего жмем «Finish»
У нас есть созданный проект. Теперь перемещаем в папку libs библиотеку classes.jar, о которой говорил выше
Открываем UnityTorchActivity.java в папке src, он выглядит так
Для того, чтобы наш плагин мог работать с Unity3D, наш activity должен наследоваться от UnityPlayerActivity
Изменяем файл до такого состояния
Как мы видим, здесь ничего не происходит. Теперь нам надо написать класс Torch.java, который отвечает за фонарик и содержит функции, которые его включают/выключают. Немного гугла, и у нас готов такой класс
Внимание! Может возникнуть ошибка, связанная с activity.getPackageManager(). Для ее исправления в файле AndroidManifest.xml можно изменить строчку «android:minSdkVersion=»8″» на «android:minSdkVersion=»9″», и все будет ОК
Финальная часть — делаем в главном классе экземпляр Torch
Unity3D
Создаем проект в Unity3D
Все плагины для Android обязаны храниться в папке Assets/Plugins/Android, иначе юнити «не увидит» плагин — создаем эту папку. Туда можно будет кидать AndroidManifest.xml, jar-файлы библиотек, папку res для хранения ресурсов
Теперь возвращаемся обратно в проект в Eclipse, жмем: правой кнопкой мыши по проекту в разделе слева — «Export» — «JAR file» — «Next» — пишем путь до Assets/Plugins/Android нашего Unity-проекта — «Finish»
Создаем прямо в Unity в той же папке AndroidManifest.xml — не прямо в редакторе, а в проводнике, либо в IDE (Visual Studio, MonoDevelop)
Пишем в этом файле
То, что надо будет изменять вам — это название package, android:name у activity и uses-permisson’ы
Манифест из Eclipse-проекта не копируем, он нам не нужен
Теперь надо создать небольшую «обертку» над библиотекой — создаем два файла: TorchActivity.cs и Torch.cs
TorchActivity.cs (не забываем про package name)
Зачем нам два поля activityClass и activityObj? Через activityObj мы можем вызывать методы UnityTorchActivity, а статические функции можно вызывать только через activityClass. Такой небольшой (и подлый для новичков) нюанс
В остальном все довольно прозрачно — запуск функций вне Android платформы ни к чему хорошему не приводит
Выводы — написание плагинов под Android для Unity3D является не особо широкой практикой, из-за чего статей про это направление почти нет. Надеюсь, что привнес ясность в этот вопрос. Спасибо за внимание!
Источник