Version: 2022.3
Specify Unity start-up arguments
Deep linking on Android

将 Unity 集成到 Android 应用程序中

本页说明如何使用“Unity 用作库”功能将 Unity 运行时库集成到 Android 应用程序中。

使用此功能可以在应用程序中包含 Unity 支持的功能(例如 3D/2D 实时渲染、AR 体验、3D 模型交互或 2D 迷你游戏)。Unity 运行时库公开了多种控件来管理何时以及如何在应用程序中加载、激活和卸载内容。

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 to work properly for Android. Plug-ins that make changes to Gradle manifests need to use the the Gradle changes outlined in Using Unity as a library in native iOS/Android apps.

工作原理

从 Unity 构建 Gradle 项目时,无需进行任何其他操作。

Unity 生成的每个 Android Gradle 项目都具有以下结构:

  • 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.

要将 Unity 集成到另一个 Android Gradle 项目中,必须通过 settings.gradle 文件将生成的 Android Gradle 项目的 unityLibrary 模块包含在您的 Android Unity 项目中。

代码仓库包含示例项目和插件(演示如何将 Unity 集成到 Android 应用程序中)以及更多文档。

要控制播放器,请转发 Intent 以启动 Unity 活动并在必要时对其进行扩展。如需了解更多信息,请参阅有关 Intent 和 Intent 过滤器 (Intents and Intent Filters) 的 Android 开发者文档。还可以使用 UnityPlayer Java API。

IUnityPlayerLifecycleEvents

IUnityPlayerLifecycleEvents 提供一种与 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, 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.

可将 IUnityPlayerLifecycleEvents 的实例传递到 UnityPlayer 构造函数或者覆盖 UnityPlayerUnityPlayerActivity 子类中的方法。

限制

Unity 不会控制运行时生命周期,因此“Unity 用作库”可能并不适用于所有可能的用例。已知限制包括:

  • 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 isn’t compatible with the Xamarin app platform.

其他资源

Specify Unity start-up arguments
Deep linking on Android